0
0
Swiftprogramming~5 mins

Type casting with as, as?, as! in Swift

Choose your learning style9 modes available
Introduction

Type casting helps you change or check the type of a value so you can use it in the right way.

When you have a general object but want to use it as a specific type.
When you want to safely check if a value can be treated as another type.
When you are sure a value is a certain type and want to convert it directly.
When working with class hierarchies and you want to access subclass features.
When you want to avoid errors by safely trying to cast a value.
Syntax
Swift
value as Type
value as? Type
value as! Type

as is used for upcasting or bridging types and always succeeds.

as? tries to cast safely and returns an optional (may be nil).

as! force casts and crashes if it fails.

Examples
Using as to treat an Int as Any type.
Swift
let number = 5
let anyValue: Any = number

// Upcasting (always works)
let anyNumber = number as Any
Using as? to safely try to cast Any to String.
Swift
let anyValue: Any = "Hello"

// Safe downcast returns optional String?
let stringValue = anyValue as? String
Using as! to force cast Any to String.
Swift
let anyValue: Any = "Hello"

// Force downcast to String (crashes if wrong)
let stringValue = anyValue as! String
Sample Program

This program shows how to use as, as?, and as! with classes. It upcasts a Dog to Animal, safely downcasts back to Dog, and force downcasts to Dog.

Swift
class Animal {}
class Dog: Animal {
    func bark() -> String {
        return "Woof!"
    }
}

let animal: Animal = Dog()

// Upcast: Dog to Animal (always works)
let someAnimal = animal as Animal

// Safe downcast: Animal to Dog?
if let dog = animal as? Dog {
    print(dog.bark())
} else {
    print("Not a dog")
}

// Force downcast: Animal to Dog
let forcedDog = animal as! Dog
print(forcedDog.bark())
OutputSuccess
Important Notes

Use as? when you are not sure if the cast will work to avoid crashes.

Use as! only when you are 100% sure the cast will succeed.

as is mostly for upcasting or bridging types like Int to Any.

Summary

as is for guaranteed casts like upcasting.

as? safely tries to cast and returns an optional.

as! force casts and crashes if it fails.