DevPrep

All topics › Modern Swift

some vs any (opaque types vs existentials)?

Senior PRO

The idea

protocol Shape { func area() -> Double }
struct Circle: Shape { let r: Double; func area() -> Double { .pi * r * r } }
struct Square: Shape { let side: Double; func area() -> Double { side * side } }

func unitCircle() -> some Shape { Circle(r: 1) }      // one hidden type
func describe(_ s: some Shape) -> Double { s.area() } // = <S: Shape>(_ s: S)

let shapes: [any Shape] = [Circle(r: 1), Square(side: 2)]  // different types
let ints: any Collection<Int> = [1, 2, 3]   // constrained existential

func pick(_ big: Bool) -> some Shape {
    // if big { return Square(side: 2) } else { return Circle(r: 1) }
    // error: function declares an opaque return type, but the return
    // statements in its body do not have matching underlying types
    Circle(r: big ? 2 : 1)
}
_ = describe(shapes[0])   // implicit opening: any Shape → generic S (SE-0352)

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store