Skip to content

Instantly share code, notes, and snippets.

@jamesrochabrun
Created March 28, 2017 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesrochabrun/9d7d32bd8802be60e9b2f1dc64ec6bbb to your computer and use it in GitHub Desktop.
Save jamesrochabrun/9d7d32bd8802be60e9b2f1dc64ec6bbb to your computer and use it in GitHub Desktop.
//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