Swift some and any
In Swift, both some P and any P can mean "a type that conforms to protocol P", but they mean completely different things.
some isopaque type: hides the concrete type from the outside, but the compiler knows it is one uniquely determined type.
any isexistential type: at runtime can hold any type conforming to P, at the cost of losing static type information.
This article is based on Swift 6.x, and the examples can be run directly.
Why do we need both forms?
First consider a common need: a function returns something only required to satisfy a certain protocol, and you don't want to expose the concrete type.
Swift offers two paths, one is some and one is any; they solve different problems.
| Comparison Item | some P (opaque type) | any P (existential type) |
|---|---|---|
| Concrete type | Fixed to one type at compile time | Can be any conformer at runtime |
| Type information | Invisible to the caller, visible to the compiler | Erased |
| Can it hold different types? | No | You can |
| How to call | Static dispatch | Dynamic dispatch, with boxing overhead |
| Typical use | Hiding implementation details, SwiftUI's body | Heterogeneous collections, types determined only at runtime |
Let's explore each in turn.
Opaque return type some
Writing some before a protocol name in the return type means "I return a type conforming to this protocol, but I won't tell you which specific type".
The caller can only use members declared in the protocol; they can't see the concrete type and therefore can't rely on implementation details.
Example
import Foundation
protocol RunoobShape
{
func area
(
)
Double
}
struct
RunoobCircle
:
RunoobShape
{
var radius
:
Double
func area
(
)
Double
{
.
pi
radius
radius
}
}
struct
RunoobSquare
:
RunoobShape
{
var side
:
Double
func area
(
)
Double
{
side
side
}
}
// Returning some: the caller only knows "this is a RunoobShape"; the concrete type is hidden
func makeCircle
(
_ radius
:
Double
)
some RunoobShape
{
return
RunoobCircle
(
radius
:
radius
)
}
let circle
=
makeCircle
(
2.0
)
(
String
(
format
:
"Circle area: %.4f"
, circle.
area
(
)
)
)
(
"Static type is (type(of: circle))"
)
Running result:
圆面积:12.5664
静态类型是 RunoobCircle
Notice the output of the last line: type(of:) still returns the real RunoobCircle.
Because what some hides is thecompile-time static type, the runtime object itself is still that concrete type; you just can't write its name in code.
A function can only return one type
some requires the underlying type of all return statements in a function to be exactly the same, otherwise the compiler reports an error.
Example
protocol RunoobShape
{
func area
(
)
Double
}
struct
RunoobCircle
:
RunoobShape
{
var radius
:
Double
func area
(
)
Double
{
.
pi
radius
radius
}
}
struct
RunoobSquare
:
RunoobShape
{
var side
:
Double
func area
(
)
Double
{
side
side
}
}
func makeShape
(
_ isCircle
:
Bool
)
some RunoobShape
{
if
isCircle
{
return
RunoobCircle
(
radius
:
1.0
)
}
return
RunoobSquare
(
side
:
1.0
)
}
Compile error:
error: function declares an opaque return type 'some RunoobShape',
but the return statements in its body do not have matching underlying types
note: return statement has underlying type 'RunoobCircle'
note: return statement has underlying type 'RunoobSquare'
This need to "possibly return multiple types" is exactly where any shines.
Existential type any
Writing any followed by a protocol name gives you a "box" that can hold any conformer; the box remembers at runtime what type is actually inside.
The same variable can hold a circle first and then a square, and an array can mix different types.
Example
import Foundation
protocol RunoobShape
{
func area
(
)
Double
}
struct
RunoobCircle
:
RunoobShape
{
var radius
:
Double
func area
(
)
Double
{
.
pi
radius
radius
}
}
struct
RunoobSquare
:
RunoobShape
{
var side
:
Double
func area
(
)
Double
{
side
side
}
}
// any: existential type; one variable can hold different conformers in turn
var shape
:
any RunoobShape
=
RunoobCircle
(
radius
:
1.0
)
(
String
(
format
:
"Area: %.4f"
, shape.
area
(
)
)
)
shape
=
RunoobSquare
(
side
:
3.0
)
(
String
(
format
:
"Area: %.4f"
, shape.
area
(
)
)
)
// An array can mix different types; this is a typical use of any
let shapes
:
[
any RunoobShape
]
=
[
RunoobCircle
(
radius
:
1.0
)
,
RunoobSquare
(
side
:
2.0
)
,
RunoobCircle
(
radius
:
3.0
)
]
var total
=
0.0
for
s in shapes
{
total
=
s.
area
(
)
}
(
String
(
format
:
"Total area: %.4f"
, total
)
)
(
"Element count: (shapes.count)"
)
Running result:
面积:3.1416
面积:9.0000
总面积:35.4159
元素个数:3
The shapes array contains both circles and squares, which is impossible with some.
Note:Since Swift 5.7, writing a protocol type requires you to explicitly add any, for example any RunoobShape. Writing just RunoobShape produces a warning telling you to use any or generics instead.
Choosing between some and any
The two are not substitutes for each other; each has its suitable scenarios. The criterion is simple: does the call site need to handle multiple concrete types at once?
| Scenario | Recommended approach | Reason |
|---|---|---|
| The function returns only one implementation and you want to hide details | some P | Static dispatch, no overhead |
| Need to return multiple implementations, determined by parameters | any P | Type can switch at runtime |
| Mix different conformers in arrays or dictionaries | any P | Heterogeneous collections require existential types |
| Write generic algorithms, with the type determined by the caller | Generics |
Preserve full type information, best performance |
Rule of thumb: use generics when you can, use some when you need to hide implementation, and use any only when you truly need runtime polymorphism.
SwiftUI's var body: some View is a typical use of opaque types: each view's body returns one concrete view, but only the View protocol is exposed to the outside.
Primary associated types
A protocol with associated types can declare a "primary associated type" in angle brackets after the protocol name, after which you can write the associated type directly in type expressions.
Collection's primary associated type is Element, so you can write Collection
Example
import Foundation
// Collection's primary associated type is Element; you can write constraints directly in angle brackets
func runoobFirstInt
<
C
:
Collection
<
Int
(_ values
:
C
)
Int
?
{
return
values.
first
}
(
runoobFirstInt
(
[
10
,
20
,
30
]
)
??
1
)
// Return some Collection
func runoobNumbers
(
)
some Collection
<
Int
{
return
[
1
,
2
,
3
,
4
,
5
]
}let numbers
=
runoobNumbers
(
)
(
"Element count: (numbers.count)"
)
(
"First element: (numbers.first!)"
)
// any Collection
var anyCollection
:
any Collection
<
Int
=
[
1
,
2
,
3
]
print
("Element count: (anyCollection.count)"
)
anyCollection
=
Set
(
[
1
,
1
,
2
,
3
]
)
(
"Count after deduplication: (anyCollection.count)"
)
Running result:
10
元素个数:5
第一个元素:1
元素个数:3
去重后个数:3
Custom protocols can also declare primary associated types; just mark them in angle brackets after the protocol name.
Example
// Declare Item as the primary associated type
protocol RunoobContainer
<
Item
{associatedtype Item
var count
:
Int
{
get
}
}
// After that you can write RunoobContainer
func runoobCount
<
C
:
RunoobContainer
<
Int
(_ container
:
C
)
Int
{
return
container.
count
}
struct
RunoobIntBox
:
RunoobContainer
{
typealias Item
=
Int
var count
:
Int
}
(
runoobCount
(
RunoobIntBox
(
count
:
7
)
)
)
Running result:
7
Conformers must make Item match the Int in the constraint, otherwise the compiler reports "types are not equal".
Common questions
Finally, let's answer a few questions that commonly trip people up in real coding.
Can some be used on properties?
It can be used on computed properties, such as var body: some View; but it cannot declare stored properties, because stored properties need an exact type and memory layout.
Does any have performance issues?
There is some overhead. Existential types need boxing, and method calls use dynamic dispatch; if called frequently in hot code, prefer generics or some.
How do I recover the concrete type from any?
Use as? to downcast, then after a successful check access members unique to the concrete type; for details see "Swift Type Casting》。
Why does SwiftUI's body use some rather than any?
Because each view's body returns only one concrete view type, using some avoids boxing and uses static dispatch, while not exposing implementation details to users.