Swift Type Casting
Swift Type Casting
Use as, as?, and as! to convert between types, especially with protocols and Any.
Upcasting and Downcasting
Convert a value to a supertype (upcast) or attempt to convert back to a subtype using optional downcasting with as?.
Example
let items: [Any] = [1, "Swift"]
for item in items {
if let i = item as? Int {
print("Int: \(i)")
} else if let s = item as? String {
print("String: \(s)")
}
}
This example conditionally casts values from Any to their concrete types.
Forced Downcast
Use as! only when you are certain of the runtime type. If the cast fails, the program will crash.
Prefer optional casting (as?) when the type may vary, and unwrap safely.