Hands-On Swift 2 [Part 2]

In the previous tutorial, you practically saw how features like Availability Checking, Defer Actions and Error Handling came in handy to make your swift experience more powerful than ever. In this tutorial, I will walk you through a bench of other features from the Swift 2 arsenal.

The guard statement:

Swift 2 introduced the guard statement which improves the readability of condition statements. The guard statement will simply check against the condition you don’t want instead of checking the condition you want to fulfill.

Let’s take an example, copy the following code to your Swift Playground file:

import UIKit

let userCredit = 100
let itemValue = 200

func purchaseItem(){
    guard userCredit >= itemValue else{
        print("Sorry, you don't have enough funds to buy the item")
    print("Proceed with the item purchase")
    //.. Purchase operation


In the example above, you just checked towards a match with the guard statement. Sometimes, you want to take the first action when the condition is NOT met, that’s what you have done here. If the user credit is not enough, or in other words, if the condition userCredit >= itemValue is not true, then the guard statement will transfer the program control outside the guard scope using the return statement, otherwise, it will carry on the current scope.

Functions and Methods:

Swift 1, the previous release of Swift, followed Objective-C standards when it comes to calling functions and methods. Consider the following global function and its call:

func someMath(operand1: Int, operand2: Int){
    // Doing some math here..

someMath(1, 2)

Note: A global function is a self-contained snippet of code which is not contained in some other types (like classes), and is commonly called simply a function. While a method (aka instance method) still a function, BUT that is associated (or contained) with some particular types, like a class, structure or enum.

The example above shows a function with two parameters and a call to that function. If you try that code in a Swift 1 Playground (with Xcode 6), it will pass successfully because Swift 1 allow you to omit argument labels when you call global functions.

In other words, Swift 1 doesn’t allow to call the global function with argument labels. To fix the error in Swift 2, change the someMath function call to the following:

someMath(1, operand2: 2)

The operand2 in the function call above is called an argument label. If you run the above function call in Swift 1 Playground (Xcode 6), you will face a pretty red running error, something like:

Extraneous argument label 'operand2:' in call

The point here is that, in Swift 1, no labels are allowed for global function arguments, and only methods are allowed to be called with argument labels (for the second argument and later).

In swift 2, this is no longer the case, and all ‘func’ (global functions and methods) have now a uniform declarations.

What does that mean?

To better understand, copy the following code inside a Swift 2 Playground (Xcode 7 Playground):

class Store {
    func buyWeapons(userCredit: Double, itemCount : Int){
        // Some code..

func buyWeapons(userCredit: Double, itemCount : Int){
     // Some code..

let store = Store()
store.buyWeapons(300, itemCount: 2)

buyWeapons(400, itemCount: 5)

The code above declares two func types with the same names and definitions, an instance method inside the Store class and a global function outside the class scope, then it performs a call for both func.

You may notice both calls are preformed with the same manner, which means the first argument is implicitly implied by the base function name and the second argument is labeled. Unlike Swift 1, Swift 2 unifies the arguments labels way for both the functions and methods to look the same when you call them 🙂

This will remove a lot of confusion when you read your code, if the func is an instance method, you will notice that only from the dot notation (store.buyWeapons).

Argument Labels Controls:

You just saw how func types are defined and called in Swift 2, however, there is even more. When you call a function, you don’t have to specify a label for the first argument because that’s inferred by Swift to the function name. That’s said, you can still explicitly name the first argument by specifying an external parameter in the function definition.

Let’s take the following example to understand, copy the code below inside the Playground file:

func buyWeapons(withCredit userCredit: Double, howManyItems itemCount : Int){
     // Some code..

The above function has two parameters, in addition to the local parameter names (userCredit and itemCount), both parameters have external parameters names called withCredit and howManyItems respectively, written before the local parameter names and separated by a space.

By specifying an external parameter name for each parameter, the call for the function will change to the following:

buyWeapons(withCredit: 500, howManyItems: 4)

Here is how you call the function with and without external parameter names:

// If the function is defined without external parameter names
buyWeapons(400, itemCount: 5)
// If the function has external parameters names 
buyWeapons(withCredit: 500, howManyItems: 4)

External parameter names are very useful, it will improve the readability of your code, hence, you won’t need to refer to the function definition somewhere in your code to understand the purpose of each argument you pass to the function 🙂

Where to go from here ?

Swift 2 is here to boost your app performance and make your programming experience easier than ever. I strongly recommend you read the official Swift guide written by Apple to better understand all the language aspects.

Feel free to leave a comment below if you have any question, I’d love to hear from you 🙂

iOS developer with over than 11 years of extensive experience working on several projects with different sized startups and corporates.

1 Comment

  1. Hello,

    This is really an informative blog for all the beginners as well as app developers. App demand will surely increase day by day, as it is the main reason behind the business success.

    I am an iOS app developer, I have tried most of the mobile app development platforms. I have developed more than 50 apps till today with the help of Phonegap, Telerik, Configure.IT etc. They are running successfully on app store.

    As per my experience in this field, I recommend developers as well as beginners to use mobile app development platform like Configure.IT, because it provides automatic coding, app preview facility, direct API connect and a lot more features. These things save a lot more development time and provides fast and well designed app in much less time.

    Read more: http://www.configure.it/features/mobile-app-configuration/

    Swift is a nice language to develop an app but it takes more times and efforts to develop an app compared to mobile app development platform.

Comments are closed.