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: [anyPlace] = [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 isCafe { cafes += 1 }iflet station = place as? Station {print("\(station.name) has \(station.lines.count) lines") }}print("cafes: \(cafes)")let note = describe(places[2])print(note)protocolPlace {var name: String { get }funcpin() -> String}structCafe: Place {let name: Stringlet seats: Intfuncpin() -> String {"[cafe] \(name)" }}structStation: Place {let name: Stringlet lines: [Int]funcpin() -> String {"[train] \(name)" }}structPark: Place {let name: Stringlet dogsAllowed: Boolfuncpin() -> String {"[park] \(name)" }}funcdescribe(_ place: anyPlace) -> String {switch place {caselet cafe asCafewhere cafe.seats > 10:return"\(cafe.name): roomy cafe"caseisCafe:return"small cafe"caselet park asPark:return park.dogsAllowed ? "\(park.name): dogs welcome" : "\(park.name): no dogs"default:return"\(place.name): just a place" }}
Swift code does not run on this page. Save your edited code as main.swift on your own computer, compile it with swiftc and run it.
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: anyPlace = 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: anyPlace = Cafe(name: "Nook", seats: 6)iflet 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: anyPlace = Park(name: "Hill", dogsAllowed: false)switch spot {caseisCafe:print("cafe")caseisPark:print("park")}
What the Swift compiler sayserror: switch must be exhaustive
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: anyPlace = Station(name: "Port", lines: [4])let station = stop asStationprint(station.lines)
What the Swift compiler sayserror: 'any Place' is not convertible to 'Station'
Fixed
let stop: anyPlace = Station(name: "Port", lines: [4])iflet 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: anyPlace = 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: anyPlace = 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.