TIL in Swift, s
in let s = optionalString
will be 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"
}