Type Checking & Casting in Swift
From the Swift cheat sheet · Type Casting · verified Jul 2026
Type Checking & Casting
is, as, as?, as! operators
swift
// Type checking with 'is'
let items: [Any] = [1, "hello", 3.14, true]
for item in items {
if item is Int {
print("Integer: \(item)")
} else if item is String {
print("String: \(item)")
} else if item is Double {
print("Double: \(item)")
}
}
// Downcasting with as? and as!
class Animal {
var name: String
init(name: String) {
self.name = name
}
}
class Dog: Animal {
func bark() {
print("Woof!")
}
}
class Cat: Animal {
func meow() {
print("Meow!")
}
}
let animals: [Animal] = [Dog(name: "Rex"), Cat(name: "Whiskers")]
for animal in animals {
if let dog = animal as? Dog {
dog.bark()
} else if let cat = animal as? Cat {
cat.meow()
}
}💡 Use is for type checking, as? for safe casting
⚡ Avoid as! force casting - it crashes if cast fails
📌 Any can hold any type, AnyObject only class instances
🟢 Swift automatically bridges to Objective-C types when needed