Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 146 ยท Structures, Classes and Enums

Type Casting

Learn Swift type casting - checking types with is, safe downcasts with as?, forced as!, upcasting with as, Any and AnyObject, switch patterns, protocols and when to avoid casts.

Swift is a statically typed language: nearly every value has a type that the compiler knows. But sometimes a variable's type is only partly known. A list of Animal objects may secretly hold Dog and Cat instances. A function that accepts Any can receive anything. JSON decoded by hand gives you Any values. In those moments you need to ask the question "what is this really?" and, if the answer suits you, treat the value as that more specific type.

That question and that conversion are type casting. Swift gives you the operator is to check a type, as? to try a conversion safely, as! to force one, and plain as for conversions that can never fail. This lesson explains each, how casting works with class hierarchies, Any, AnyObject and protocols, and why in modern Swift the best cast is often the one you do not need. It builds on classes, inheritance and optionals.

A class hierarchy to cast in

Casting is easiest to understand with a small hierarchy. Dog and Cat are subclasses of Animal:

Swift Subclasses and a mixed array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The array has the static type [Animal], so the compiler only lets you use what every Animal has. Yet type(of:) reports the dynamic type, the real class of each object at run time: Dog, Cat, Dog. The commented-out line would not compile: an Animal is not guaranteed to be a dog. To call fetch() you must prove (or promise) the object is a Dog.

Checking a type with is

The is operator returns true when a value is of a certain type, or of a subclass of it:

Swift The is operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

is works with a subclass check: a Dog is an Animal. It also works with protocols and with any type. But is only answers yes or no. If you then want to use the dog as a dog, you need the next operator.

Downcasting with as?

A downcast converts a value to a more specific subclass type. Because it can fail, the safe form as? returns an optional: the converted value, or nil if the object is not of that type.

Swift Safe downcasting with as?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The pattern if let dog = pet as? Dog is the idiom to learn: it checks the type and gives you the value under its more specific type in one step. Inside the if body, dog is a Dog and fetch() is available. Using compactMap with as? is a compact way to filter a collection by type: failed casts produce nil, and compactMap drops them.

Forced casts with as!

If you are certain, as! skips the optional and gives the converted value directly. If you are wrong, the program traps.

Swift A forced cast that fails (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output stops after about to cast. The process aborts (SIGABRT) after printing a message on the error stream, which here reads Could not cast value of type 'binary.Cat' (0x...) to 'binary.Dog' (0x...); the module is called binary in this runner and the addresses differ on every run. Treat as! like ! on optionals: acceptable when a wrong type is a bug in your own program that should stop it, and risky anywhere the data comes from outside. In most cases as? combined with guard let or if let is better:

Swift
// Read-only example: the safe version of the same idea
guard let dog = pet as? Dog else {
    print("not a dog, skipping")
    return
}

Upcasting and bridging with as

The plain as operator performs a conversion that always succeeds and is checked at compile time. The most common case is an upcast, treating a subclass instance as its superclass:

Swift Upcasts and the compile-time check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

An upcast changes only the static type; the object is the same, and type(of:) still reports Dog. In everyday code you rarely write an explicit upcast, because assignment does it implicitly. You will see as mostly to guide the type of a literal or to disambiguate overloads. If you try to use as for a conversion that could fail, the compiler rejects it:

Swift as cannot downcast (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The error is error: 'Animal' is not convertible to 'Dog' with a note suggesting as! to force the failable cast. Swift is telling you that a downcast may fail, so you must write as? or as! to show that you thought about it.

Any and AnyObject

Swift has two special types for "anything":

  • Any can hold a value of any type at all: integers, strings, structs, functions, optionals, classes.
  • AnyObject can hold an instance of any class.

They are called existential types: a box that can contain any type conforming to a requirement (here, none). Use them sparingly, since they throw away the compiler's knowledge, but they are the honest type for truly mixed data:

Swift A mixed array of Any

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

switch over an Any with case let x as Type is the standard way to branch on dynamic type. The cases are tested in order and each pattern both checks the type and binds the converted value. The default is required because the list of possible types is infinite. Note the order matters when types overlap: if case let n as Int came after a case for Any, the later one would never run.

When you put an optional into an Any, Swift warns: expression implicitly coerced from 'Int?' to 'Any'. The optional becomes a boxed value that may print as Optional(5) or even nil inside an Any. Unwrap it first, or make the intention explicit with as Any, as the earlier lessons do when printing optionals.

AnyObject and class-only code

AnyObject is the type of "some class instance". It appears in older APIs, in weak delegate declarations (protocol P: AnyObject) and when you want to compare identity with ===:

Swift AnyObject and identity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Two tokens with the same id are still different objects, so === is false. On Apple platforms AnyObject can also hold bridged value types such as String and Array; on Linux, as here, you should treat it as "class instances only". In new code you will use AnyObject mostly as a protocol constraint ("class-bound"), covered in Protocol Composition and Delegation.

Casting to protocols

Casting works with protocols as well. This lets you ask "does this value have a capability?" and use it if so:

Swift Casting to a protocol

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

item as? Describable succeeds for the structs and classes that conform, and fails for Coin. Writing any Describable is the modern spelling for the existential box, and Swift 6 requires you to say any in more places. Opaque and Existential Types explains the difference between some and any.

Casting numbers and bridging

A frequent surprise is that as? does not convert numbers between types. It tests whether the value is that exact type:

Swift as? does not convert numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

7 stored in an Any is an Int, so as? Double is nil. To change the representation of a number, use an initializer such as Double(i); to parse text, use Int(text), which returns an optional (Basic Types). Type casting is about which type a value already has, not about turning one kind of data into another.

Casts versus better designs

Casting is a tool for the moments when static types are not enough. If you find many as? in a codebase, look for a design that removes them:

  • Polymorphism. Instead of testing pet is Dog then calling fetch, put a method play() on Animal and override it in each subclass. The right version is chosen automatically (Inheritance).
  • Enums with associated values. If you have a fixed set of kinds, an enum lets switch check every case with no default and no casts.
  • Generics and protocols. A generic function func f<T: Describable>(_ x: T) knows the type at compile time and needs no cast.
  • Codable. For JSON, decode into typed structs (Codable) instead of poking at [String: Any] with as?.

Casts remain right for legacy APIs, heterogeneous collections that are truly open ended, plug-in systems, and tests. When you do cast, prefer as? and handle failure; reserve as! for places where a failure is a programmer error.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does pet as? Dog produce when pet actually holds a Cat?

    The conditional downcast returns an optional. When the object is not of the requested type, the result is nil and nothing crashes.
  2. 2. Which operator should you use when the cast might fail and you want to handle that safely?

    as? returns an optional you can unwrap. as! traps on failure, plain as only compiles for conversions that cannot fail, and is gives only a Boolean.
  3. 3. What does type(of: animal) report for let animal = Dog(name: "Rex") as Animal?

    An upcast changes the static type only. At run time the object is still a Dog, and type(of:) reports the dynamic type.
  4. 4. Given let value: Any = 7, what is value as? Double?

    The value inside the Any is an Int, and as? checks the exact type rather than converting. Use Double(i) to convert.
  5. 5. How do you branch on the dynamic type of a value stored in Any?

    A switch with case let x as Type patterns tests each type in order and binds the converted value.

Summary

  • is checks whether a value is of a type (or a subclass); as? downcasts safely and returns an optional; as! forces the cast and traps on failure; as performs conversions the compiler can prove.
  • Use if let x = value as? Type to check and convert in one step.
  • An upcast changes the static type only; type(of:) shows the real dynamic type.
  • Any holds any value and AnyObject any class instance; branch on them with switch and case let x as Type.
  • Casting works with protocols (item as? Describable), and any marks existential protocol types.
  • as? tests the exact type and never converts numbers; use initializers for that.
  • Prefer polymorphism, enums, generics and Codable over casts, and keep as! for genuine can't-happen cases.

Next: Nested Types and Extensions