Opaque and existential types: some and any
suggest changeA protocol can be used as a type in three ways:
- as a generic constraint:
func f<S: Shape>(_ s: S) - as an opaque type:
some Shape(return types since Swift 5.1, parameters since Swift 5.7) - as an existential type:
any Shape(theanykeyword since Swift 5.6)
some Shape means "one specific type that conforms to Shape. The compiler knows which one, but the code that uses it doesn't". any Shape means "a box that can hold a value of any type conforming to Shape, and the type can change at runtime".
The difference affects what you can store, what the compiler can check, and how fast the code runs. This article also covers primary associated types (some Collection<Int>, any Sequence<String>) and how Swift opens existentials when passing them to generic code.
The examples were compiled and run with Swift 6.4 on Windows:
swiftc -swift-version 6 main.swift -o main.exe
Most examples use this protocol and two conforming types:
protocol Shape {
var name: String { get }
func area() -> Double
}
struct Circle: Shape {
var radius: Double
var name: String { "circle" }
func area() -> Double { .pi * radius * radius }
}
struct Square: Shape {
var side: Double
var name: String { "square" }
func area() -> Double { side * side }
}
Three ways to accept a protocol
// 1. generic parameter
func describeGeneric<S: Shape>(_ shape: S) -> String {
"\(shape.name): \(shape.area())"
}
// 2. opaque parameter, same thing as 1.
func describeSome(_ shape: some Shape) -> String {
"\(shape.name): \(shape.area())"
}
// 3. existential parameter
func describeAny(_ shape: any Shape) -> String {
"\(shape.name): \(shape.area())"
}
print(describeGeneric(Square(side: 2)))
print(describeSome(Square(side: 2)))
print(describeAny(Square(side: 2)))
Output:
square: 4.0
square: 4.0
square: 4.0
All three give the same result, but they are not the same:
some Shapein a parameter is shorthand for an unnamed generic parameter.describeSomeis exactlydescribeGeneric. Each call is resolved at compile time for the concrete type, and the optimizer can specialize it.any Shapeis a single, non-generic function. The argument is wrapped in an existential box and methods are called through a witness table at runtime.
Use some when you don't need to name the type parameter. Use the full <S: Shape> form when you need the name, for example to require two parameters to have the same type (func same<S: Shape>(_ a: S, _ b: S)) or to write a where clause. See The Basics of Generics and Advanced Type Constraints.
any: existential boxes
An any Shape value can hold any conforming type, and a different one at different times. This is what you need for a heterogeneous collection:
let shapes: [any Shape] = [Circle(radius: 1), Square(side: 3), Circle(radius: 0.5)]
for shape in shapes {
print(shape.name, shape.area())
}
let total = shapes.reduce(0) { $0 + $1.area() }
print("total:", total)
var current: any Shape = Circle(radius: 2)
print(type(of: current))
current = Square(side: 2)
print(type(of: current))
if let square = current as? Square {
print("side is", square.side)
}
Output:
circle 3.141592653589793
square 9.0
circle 0.7853981633974483
total: 12.926990816987242
Circle
Square
side is 2.0
type(of:) returns the dynamic type stored in the box. You can get the concrete value back with as?.
some can't do this. Every element of [some Shape] must have the same concrete type:
func total(_ shapes: [some Shape]) -> Double {
shapes.reduce(0) { $0 + $1.area() }
}
print(total([Square(side: 1), Square(side: 2)]))
print(total([Circle(radius: 1), Square(side: 2)]))
error: conflicting arguments to generic parameter 'some Shape' ('Square' vs. 'Circle')
The any keyword is (mostly) optional for now
Before Swift 5.6 an existential was written as the bare protocol name: let s: Shape. That still compiles in Swift 6 mode for simple protocols. For protocols with associated types or Self requirements, such as Hashable, Swift 6 warns that any is required:
let old: Shape = Circle(radius: 1) // same as: any Shape
let h: Hashable = 1
warning: use of protocol 'Hashable' as a type must be written 'any Hashable'; this will be an error in a future Swift language mode [#ExistentialAny]
To get the warning for all protocols, compile with -enable-upcoming-feature ExistentialAny (in a package: .enableUpcomingFeature("ExistentialAny") in swiftSettings). Writing any everywhere makes the cost of an existential visible in the code, so it's a good habit.
some in return types: opaque results
An opaque return type lets a function return a concrete type without telling callers what it is:
func makeShape() -> some Shape {
Circle(radius: 1)
}
let s = makeShape()
print(s.name, s.area())
print(type(of: s))
Output:
circle 3.141592653589793
Circle
At runtime the value is a plain Circle, with no box. But the caller can only use what Shape offers:
print(s.radius)
error: value of type 'some Shape' has no member 'radius'
This is the reverse of a generic parameter. With <S: Shape> the caller picks the type. With -> some Shape the function picks it, and the caller only knows it conforms to Shape. The function can later return a different type without breaking callers' source code.
The rule: every return must produce the same concrete type.
func makeShape(round: Bool) -> some Shape {
if round {
return Circle(radius: 1)
} else {
return Square(side: 1)
}
}
error: function declares an opaque return type 'some Shape', but the return statements in its body do not have matching underlying types [#OpaqueTypeInference]
note: return statement has underlying type 'Circle'
note: return statement has underlying type 'Square'
If you really need to return different types, return any Shape:
func makeShape(round: Bool) -> any Shape {
if round {
return Circle(radius: 1)
} else {
return Square(side: 1)
}
}
print(makeShape(round: false).name)
Output:
square
Type identity
The compiler knows the hidden type, so results of the same function have the same type. You can put them in one array, and you can use them with protocols that have Self requirements, like Equatable:
func makeShape() -> some Shape { Square(side: 3) }
var pair = [makeShape(), makeShape()] // both elements have the same type
pair.append(makeShape())
print(pair.count, pair.map { $0.area() })
let local: some Shape = Circle(radius: 2)
print(local.name)
Output:
3 [9.0, 9.0, 9.0]
circle
The identity is tied to the function, not to the underlying type. A second function makeOther() -> some Shape that also returns a Square gives a different opaque type, and pair.append(makeOther()) fails with cannot convert value of type 'some Shape' (result of 'makeOther()') to expected argument type 'some Shape' (result of 'makeShape()').
The same matters for Equatable:
func makeID() -> some Equatable {
42
}
let a = makeID()
let b = makeID()
print(a == b)
func makeAnyID() -> any Equatable {
42
}
let x = makeAnyID()
let y = makeAnyID()
print(x == y)
error: binary operator '==' cannot be applied to two 'any Equatable' operands
a == b compiles because both values are the same (hidden) type. Two any Equatable values could hold an Int and a String, so == (which needs both sides to be Self) can't be called.
The most famous use of opaque results is SwiftUI's var body: some View. A view's real type is a long nested generic type that nobody wants to write. The same is true for lazy sequence chains, as the next section shows.
Primary associated types
Swift 5.7 lets a protocol declare primary associated types in angle brackets, like protocol Sequence<Element> and protocol Collection<Element>. Then you can constrain them directly in some and any:
func evens(upTo limit: Int) -> some Sequence<Int> {
stride(from: 0, through: limit, by: 2)
}
func squares(of numbers: some Collection<Int>) -> [Int] {
numbers.map { $0 * $0 }
}
print(Array(evens(upTo: 10)))
print(squares(of: [1, 2, 3]))
print(squares(of: 1...4))
print(squares(of: Set([5])))
let lazyNames = ["ana", "bob", "cy"].lazy.filter { $0.count > 2 }.map { $0.uppercased() }
print(type(of: lazyNames))
func shout(_ names: [String]) -> some Sequence<String> {
names.lazy.filter { $0.count > 2 }.map { $0.uppercased() }
}
for name in shout(["ana", "bob", "cy"]) {
print(name)
}
Output:
[0, 2, 4, 6, 8, 10]
[1, 4, 9]
[1, 4, 9, 16]
[25]
LazyMapSequence<LazyFilterSequence<Array<String>>, String>
ANA
BOB
Without <Int> you would write func squares<C: Collection>(of numbers: C) -> [Int] where C.Element == Int. And shout would have to spell out LazyMapSequence<LazyFilterSequence<Array<String>>, String>, or return an Array and lose laziness.
Constrained existentials work the same way:
let sources: [any Sequence<String>] = [
["a", "b"],
Set(["c"]),
"d e".split(separator: " ").map(String.init),
repeatElement("z", count: 2),
]
for source in sources {
print(type(of: source), Array(source))
}
var numbers: any Collection<Int> = [3, 1, 2]
print(numbers.count, numbers.first!)
numbers = 10..<13
print(numbers.count, numbers.first!)
Output:
Array<String> ["a", "b"]
Set<String> ["c"]
Array<String> ["d", "e"]
Repeated<String> ["z", "z"]
3 3
3 10
Before Swift 5.7 this needed hand-written type erasers such as AnySequence<String>. They still exist, but any Sequence<String> is usually enough.
Declaring your own
Put the associated type names after the protocol name. The associatedtype declaration stays in the body (see Associated type requirements):
protocol Store<Item> {
associatedtype Item
mutating func add(_ item: Item)
var items: [Item] { get }
}
struct MemoryStore<Item>: Store {
var items: [Item] = []
mutating func add(_ item: Item) { items.append(item) }
}
struct UniqueStore<Item: Hashable>: Store {
private var seen: Set<Item> = []
var items: [Item] = []
mutating func add(_ item: Item) {
if seen.insert(item).inserted { items.append(item) }
}
}
func fill(_ store: inout some Store<String>, with words: [String]) {
for w in words { store.add(w) }
}
var memory = MemoryStore<String>()
var unique = UniqueStore<String>()
fill(&memory, with: ["a", "b", "a"])
fill(&unique, with: ["a", "b", "a"])
print(memory.items, unique.items)
let stores: [any Store<String>] = [memory, unique]
for store in stores {
print(type(of: store), store.items.count)
}
func makeStore() -> some Store<Int> {
UniqueStore<Int>()
}
var s = makeStore()
s.add(1); s.add(1); s.add(2)
print(s.items)
Output:
["a", "b", "a"] ["a", "b"]
MemoryStore<String> 3
UniqueStore<String> 2
[1, 2]
makeStore hides which store it uses, but callers still know the items are Int, so s.add(1) type-checks.
Without the primary type, a plain any Store doesn't know Item. Members that return Item are still usable (the type is erased to Any), but members that take Item as input are not:
var store: any Store = MemoryStore<Int>(items: [1, 2])
store.add(3)
error: member 'add' cannot be used on value of type 'any Store'; consider using a generic constraint instead [#ExistentialMemberAccess]
Opening existentials
Since Swift 5.7 you can pass an any Shape to a function that takes some Shape or <S: Shape>. The compiler "opens" the box and calls the generic function with the concrete type inside:
func describe<S: Shape>(_ shape: S) -> String {
"\(S.self) with area \(shape.area())"
}
let shapes: [any Shape] = [Circle(radius: 1), Square(side: 2)]
for shape in shapes {
print(describe(shape)) // shape is opened to Circle, then Square
}
Output:
Circle with area 3.141592653589793
Square with area 4.0
Inside describe, S is the real type, not any Shape. This is the standard way to get from an existential back to generic code, which is faster and can use Self and associated types.
The same trick lets you compare two any Equatable values:
func isEqual(_ lhs: any Equatable, _ rhs: any Equatable) -> Bool {
func compare<T: Equatable>(_ lhs: T) -> Bool {
guard let rhs = rhs as? T else { return false }
return lhs == rhs
}
return compare(lhs) // lhs is opened: T becomes its concrete type
}
print(isEqual(42, 42))
print(isEqual(42, 43))
print(isEqual("42", 42))
print(isEqual("swift", "swift"))
Output:
true
false
false
true
Opening only works for a single value. An any Shape box does not itself conform to Shape, so an array of boxes can't be passed where an array of one concrete type is expected:
func total<S: Shape>(_ shapes: [S]) -> Double {
shapes.reduce(0) { $0 + $1.area() }
}
let shapes: [any Shape] = [Circle(radius: 1), Square(side: 2)]
print(total(shapes))
error: type 'any Shape' cannot conform to 'Shape' [#ProtocolTypeNonConformance]
note: only concrete types such as structs, enums and classes can conform to protocols
Make total take [any Shape], or loop and open each element.
Performance and memory
An existential is a fixed-size container. It has 3 words of inline storage for the value, plus pointers to the type's metadata and to its protocol witness table. Values that don't fit inline are stored on the heap. An opaque value is just the value itself:
struct Box: Shape {
var w, h, d, extra: Double
var name: String { "box" }
func area() -> Double { w * h }
}
func makeCircle() -> some Shape { Circle(radius: 1) }
print("Circle: ", MemoryLayout<Circle>.size)
print("Box: ", MemoryLayout<Box>.size)
print("some Shape: ", MemoryLayout.size(ofValue: makeCircle()))
print("any Shape: ", MemoryLayout<any Shape>.size)
print("any AnyObject", MemoryLayout<AnyObject>.size)
Output (64-bit):
Circle: 8
Box: 32
some Shape: 8
any Shape: 40
any AnyObject 8
An 8-byte Circle takes 40 bytes in an any Shape. A 32-byte Box doesn't fit in the 24-byte inline buffer, so storing it in any Shape also allocates on the heap. Class-constrained existentials (AnyObject, or a protocol marked : AnyObject) need only the reference.
Calls through any use dynamic dispatch, so the optimizer can't inline them. A quick comparison that sums the areas of 10 million squares, compiled with -O:
func sumSome(_ shapes: [some Shape]) -> Double {
var total = 0.0
for s in shapes { total += s.area() }
return total
}
func sumAny(_ shapes: [any Shape]) -> Double {
var total = 0.0
for s in shapes { total += s.area() }
return total
}
let n = 10_000_000
let concrete = (0..<n).map { Square(side: Double($0 % 10)) }
let boxed: [any Shape] = concrete
let clock = ContinuousClock()
var r1 = 0.0, r2 = 0.0
let t1 = clock.measure { r1 = sumSome(concrete) }
let t2 = clock.measure { r2 = sumAny(boxed) }
print("some:", t1, r1)
print("any: ", t2, r2)
Output (timings vary between machines):
some: 0.0078949 seconds 285000000.0
any: 0.0355104 seconds 285000000.0
The some version is about 4x faster here. It is specialized for Square, area() is inlined, and the array is 5 times smaller (8 vs. 40 bytes per element). Most code won't notice the difference, but in hot loops prefer generics or some.
Which one to use
- Start with
somefor parameters and return types. It is as fast as a generic, keeps type identity, and works withSelfand associated types. - Use
<T: P>instead ofsomewhen you need to name the type: two parameters of the same type, awhereclause, or usingTin the body. - Use
anywhen the concrete type really varies at runtime: heterogeneous arrays and dictionaries, stored properties that can be swapped, or returning different types from different branches. This is the "protocol as a type" style shown in Using protocols as first class types. - Add primary associated types (
protocol Store<Item>) to your own protocols when callers will usually want to constrain that type. - To go from
anyback to generic code, pass the value to a generic orsomefunction and let Swift open it.