Introduction to Optionals (Part 2)
The second part of optionals! I get Optional Binding so we'll see what we have next...
Downsides to using If Let
Optional binding is used with the if let. The example Pasan gives highlights a couple of flaws - what if we don't have the data? Well, we would have to use else and nil.
Downsides to using If Let
Optional binding is used with the if let. The example Pasan gives highlights a couple of flaws - what if we don't have the data? Well, we would have to use else and nil.
struct Friend {
let name: String
let age: String
let address: String?
}
func new(friendDictionary: [String: String]) -> Friend? {
let name = friendDictionary["name"]
if name == nil {
return nil
}
let address = friendDictionary["address"]
}
The issue here is we would have to return the values using ! which is not recommended. The main point Pasan makes is that optional binding is laborious but it was necessary in Swift 1. From Swift 2 onwards there is supposed to be a better way....
Early Exits Using Guard
There is a Guard statement....
func newFriend(friendDictionary: [String: String]) -> Friend? {
guard let name = friendDictioary["name"], let age = friendDictionary["age"] {
else return nil
}
let address = friendDictionary["address"]
return Friend(name: name, age: age, address: address)
So there is no need for 'nested' code - brackets within brackets etc.
Challenge - had to use help to figure this out. Not too sure about the use of the guard statement - need more practice with this!
Recap
You have to be prepared for 'nil' to be returned - otherwise the program will crash.
In Swift, you can use ? to make a clear optional type, if a value can return nil.
If the type is not an optional, the compiler will warn you - more safety with the code!
We have to unwrap (a type of enum) - using if/let - an expression to evaluate if an optional is returned. This is laborious and has nested values though.
Guard statement is preferable - can lead to an 'early exit'. Else clause is used inside.
Forced unwrapping - not use this as a valid option for now!
Optionals is something that I've always found difficult but I honestly feel like I can see the purpose of them now. Let's say you have a database of values but one of them may not contain anything, nil has to be an option. The whole unwrapping process is long-winded so I will need some practice with that at some point. The next set of videos are to do with Objects and Optionals. Once I've done that, then that's the enum/optional course complete. Definitely the hardest so far, so I know that it is something to get more practice with when I'm using the Udemy courses.
Comments
Post a Comment