Created
March 28, 2017 23:48
-
-
Save jamesrochabrun/9d7d32bd8802be60e9b2f1dc64ec6bbb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//OPTIONAL BINDING | |
let weatherDictionary: [String: String] = ["currentWeather" : "22.4", "weeklyWeather" : "25.9"] | |
if let weekly = weatherDictionary["weeklyWeather"] { | |
print(weekly) | |
} | |
//prints 25.9 | |
//DOWNSIDES OF USING IF LET AND WHY GUARD SOLVE THIS | |
struct Friend { | |
let name : String | |
let age: String | |
let address: String? | |
} | |
//PROBLEM: here we are returning nil checking for all the data and sometimes we need to check just for one var and pass the others | |
func new(friendDict: [String: String]) -> Friend? { | |
if let name = friendDict["name"], let age = friendDict["age"] { | |
let address = friendDict["address"] | |
return Friend(name: name, age: age, address: address) | |
} else { | |
return nil | |
} | |
} | |
//ALTERNATIVE SOLUTION USING EARLY EXIT USING GUARD. | |
func newFriend(friendDict: [String: String]) -> Friend? { | |
guard let name = friendDict["name"], let age = friendDict["age"] else { | |
return nil | |
} | |
let address = friendDict["address"] | |
return Friend(name: name, age: age, address: address) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment