Junior — Middle
How do the some and any operators differ in condition checks or sets?
sobes.tech AI
Answer from AI
In Swift, the operators some and any are used for working with protocols but have different meanings:
-
someis a keyword for indicating opaque return types. It signifies that a function returns a specific, but hidden type that conforms to a protocol. The type is fixed but not revealed. -
anyis a keyword for creating existential types, meaning variables or parameters that can hold any type conforming to a protocol.
Example:
protocol Shape {
func area() -> Double
}
struct Circle: Shape {
var radius: Double
func area() -> Double { return .pi * radius * radius }
}
// some Shape — returns a specific, but hidden type
func makeCircle() -> some Shape {
return Circle(radius: 5)
}
// any Shape — can contain any type conforming to Shape
func printArea(of shape: any Shape) {
print(shape.area())
}
Thus, some fixes a specific type, while any allows for different types conforming to the protocol.