上QQ阅读APP看书,第一时间看更新
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 let id = jsonResponse["id"] as? Int
{
print("Valid id: \(id)")
}
else
{
print("Invalid id")
}
This will print the else statement, since the id downcast has returned nil.