Specifying Preconditions for Methods - Swift 2.0, Xcode 7 and Interface Builder - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 1. Swift 2.0, Xcode 7 and Interface Builder

1.2 Specifying Preconditions for Methods

Problem

You want to make sure a set of conditions are met before continuing with the flow of your method.

Solution

Use the guard syntax.

Discussion

The guard syntax allows you to:

1. Specify a set of conditions for your methods

2. Bind variables to optionals and use those variables in the rest of your method’s body

Let’s have a look at a method that takes an optional piece of data as the NSData type and turns it into a String only if the string has some characters in it and is not empty:

func stringFromData(data: NSData?) -> String?{

guard let data = data,

let str = NSString(data: data, encoding: NSUTF8StringEncoding)

where data.length > 0 else{

return nil

}

return String(str)

}

And then we are going to use it like so:

if let _ = stringFromData(nil){

print("Got the string")

} else {

print("No string came back")

}

We pass nil to this method for now and trigger the failure block (“No string came back”). What if we passed valid data? And to have more fun with this, let’s create our NSData instance this time with a guard. Since the NSString constructor we are about to use returns an optional value, we put a guard statement before it to ensure that the value that goes into the data variable is in fact a value, and not nil:

guard let data = NSString(string: "Foo")

.dataUsingEncoding(NSUTF8StringEncoding) where data.length > 0 else{

return

}

if let str = stringFromData(data){

print("Got the string \(str)")

} else {

print("No string came back")

}

So we can mix guard and where in the same statement. How about multiple let statements inside a guard? Can we do that? You betcha:

func example3(firstName firstName: String?, lastName: String?, age: UInt8?){

guard let firstName = firstName, let lastName = lastName , _ = age where

firstName.characters.count > 0 && lastName.characters.count > 0 else{

return

}

print(firstName, " ", lastName)

}

See Also