Swift Type Casting

Swift Type Casting

Use asas?, 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.

Example

let value: Any = 42
let i = value as! Int   // forced downcast
print(i)

Prefer optional casting (as?) when the type may vary, and unwrap safely.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *