Swift Language Downcasting


Example

A variable can be downcasted to a subtype using the type cast operators as?, and as!.

The as? operator attempts to cast to a subtype.
It can fail, therefore it returns an optional.

let value: Any = "John"

let name = value as? String
print(name) // prints Optional("John")

let age = value as? Double
print(age) // prints nil

The as! operator forces a cast.
It does not return an optional, but crashes if the cast fails.

let value: Any = "Paul"

let name = value as! String
print(name) // prints "Paul"

let age = value as! Double // crash: "Could not cast value…"

It is common to use type cast operators with conditional unwrapping:

let value: Any = "George"

if let name = value as? String {
    print(name) // prints "George"
}

if let age = value as? Double {
    print(age) // Not executed
}