Tools
Log in
English

Learn to codeSwift

Swift polymorphism

Based on Swift 6.4any · Swift 5.6+

One pin() call, many places: any Place, is, as? and switch patterns in Swift.

In one line

The same call behaving differently depending on the type actually stored. In Swift this works through class inheritance and equally through structs that conform to one protocol.

Why you need it

If the map code reads if it is a cafe ... else if it is a station ..., adding a museum means hunting down that line. When similar if chains appear on several screens, one of them gets missed.

Give every place its own pin() and let the map call place.pin(). A new kind of place brings its own pin() and nothing else changes. Branching on type that you really need goes in one switch.

Everyday picture

Think of the power button on a universal remote. Point it at the TV and the TV turns on; point it at the air conditioner and that turns on instead. One button, and each device knows how to switch itself on. A remote with a separate button per device would soon be all buttons.

Example code

main.swift · 66 lines
let places: [any Place] = [    Cafe(name: "Bean Lab", seats: 18),    Station(name: "City Hall", lines: [1, 2]),    Park(name: "Riverside", dogsAllowed: true),]for place in places {    print(place.pin())} var cafes = 0for place in places {    if place is Cafe {        cafes += 1    }    if let station = place as? Station {        print("\(station.name) has \(station.lines.count) lines")    }}print("cafes: \(cafes)")let note = describe(places[2])print(note) protocol Place {    var name: String { get }    func pin() -> String} struct Cafe: Place {    let name: String    let seats: Int     func pin() -> String {        "[cafe] \(name)"    }} struct Station: Place {    let name: String    let lines: [Int]     func pin() -> String {        "[train] \(name)"    }} struct Park: Place {    let name: String    let dogsAllowed: Bool     func pin() -> String {        "[park] \(name)"    }} func describe(_ place: any Place) -> String {    switch place {    case let cafe as Cafe where cafe.seats > 10:        return "\(cafe.name): roomy cafe"    case is Cafe:        return "small cafe"    case let park as Park:        return park.dogsAllowed ? "\(park.name): dogs welcome" : "\(park.name): no dogs"    default:        return "\(place.name): just a place"    }}

When to use it

  • Several types share one array or parameter and get the same request ([any Place])
  • Something applies to one type only: unwrap with as? and if let
  • Several branches by type: switch with case let x as T, plus where for conditions

any Place marks a box whose concrete type is decided at run time (written this way since Swift 5.6). When a single concrete type is fixed, you can write some Place instead.

In a switch, case let cafe as Cafe where cafe.seats > 10 matches a type and a condition in one line.

Common mistakes

Reading a type-only field through the protocol type

Stored as any Place, the value shows only what the protocol lists: name and pin(). Read the cafe-only seats after unwrapping with as? Cafe. If you need this often, consider adding the value to the protocol.

Wrong

let first: any Place = Cafe(name: "Nook", seats: 6)print(first.seats)

What the Swift compiler sayserror: value of type 'any Place' has no member 'seats'

Fixed

let first: any Place = Cafe(name: "Nook", seats: 6)if let cafe = first as? Cafe {    print(cafe.seats)}

When you run it6

A switch without a catch-all case

A Swift switch must cover every possibility. New types can conform to Place at any time, so a default case is required. For an enum, listing every case also works.

Wrong

let spot: any Place = Park(name: "Hill", dogsAllowed: false)switch spot {case is Cafe:    print("cafe")case is Park:    print("park")}

What the Swift compiler sayserror: switch must be exhaustive

Fixed

let spot: any Place = Park(name: "Hill", dogsAllowed: false)switch spot {case is Cafe:    print("cafe")case is Park:    print("park")default:    print("other place")}

When you run itpark

Downcasting with plain as

Plain as is only for conversions that cannot fail. Going from a protocol type to a concrete type can fail, so use as?, which gives nil on failure. as! exists too, but it stops the program when wrong.

Wrong

let stop: any Place = Station(name: "Port", lines: [4])let station = stop as Stationprint(station.lines)

What the Swift compiler sayserror: 'any Place' is not convertible to 'Station'

Fixed

let stop: any Place = Station(name: "Port", lines: [4])if let station = stop as? Station {    print(station.lines)}

When you run it[4]

Check yourself

Question 1

A park that does not allow dogs goes to describe. What is printed?

let spot: any Place = Park(name: "Hill", dogsAllowed: false)print(describe(spot))

Show the answer

Answer: 3. Hill: no dogs It matches case let park as Park, and the ternary inside picks the text for dogsAllowed == false.

Question 2

A cafe with 4 seats. What does describe return?

let spot: any Place = Cafe(name: "Dot", seats: 4)print(describe(spot))

Show the answer

Answer: 2. small cafe The first case fails its where cafe.seats > 10 condition, so the next one, case is Cafe, matches. Cases are tried from the top.

Questions people ask

What is any Place?

A box that can hold any type conforming to the Place protocol. The concrete type is decided at run time, and through the box you see only what the protocol lists. Swift 5.6 introduced writing any in front.

What is the difference between is and as?

is only answers whether the value is that type. as? returns the converted value or nil, so it pairs with if let. as! stops the program when wrong, so avoid it where you can.

Why does a switch need default?

A Swift switch must cover every case. More types can conform to a protocol later, so a default is required to compile. For an enum, listing every case also works.