Attended a workshop on “Introduction to iOS Development with Swift 4” last year on 07 Oct 2017. Got a better idea of Optionals and penned down some notes in a GitHub gist. Thought it would be better to put them in a blog post to make it more accessible 🙂
The gist of it is that, the variable s in let s = optionalString will be automatically unwrapped when used with if and guard.
var possibleString: String?
possibleString = "Hello"
/* if - without unwrap */
let s = possibleString
if (s != nil) {
print(s) // Optional("Hello")
}
/* if - with unwrap */
if let s = possibleString {
print(s) // "Hello"
}
/* guard - without unwrap */
func check(optionalString: String?) {
let s = optionalString
guard (s != nil) else {
print("nil value")
return
}
// Warning: Expression implicitly coerced from 'String?' to Any
print(s) // Optional("Hello")
}
/* guard - with unwrap */
func checkAndUnwrapped(optionalString: String?) {
guard let s = optionalString else {
print("nil value")
return
}
print(s) // "Hello"
}

