Optionals
In Chapter 2, Basic Swift, we looked at the raw basics of Swift's optionals. In this section, we'll flesh that out to cover their most essential use cases.
Conditional downcasting
We have already seen how to safely unwrap an optional value:
if let id = Int("12364677") { print("Valid id: \(id)") }
In this case, we know that the Intinit
method that takes a String
argument returns an optional Int
. We only need to test whether it contains a value or nil
, and if it contains a value, we know that we can unwrap the value to get an Int
.
If, however, we don't know what type may be returned by a function, we can attempt a downcast with the as?
keyword:
let jsonResponse: [String: Any] = ["user": "Elliot", "id": "Elliot2016"] if let userString = jsonResponse["user"] as? String { print("User string contains \(userString.characters.count) characters") }
This code will print the required information, since the downcast succeeds.
Now try this code:
if...