Understanding some and any in Swift - COFPROG

Understanding some and any in Swift

Swift's powerful type system allows for advanced features like generics and protocols. With the introduction of Swift 5.1, Apple brought in new capabilities around opaque types and type erasure using the some and any keywords. In this post, we'll explore what these keywords do and how to use them effectively. The some Keyword and Opaque Types The some keyword is used to create an opaque return type when returning an instance of a protocol. An opaque type hides the concrete type behind the protocol, giving you an abstraction layer. For example:

protocol SomeProtocol {

    func doSomething()

}


struct ConcreteType: SomeProtocol {

    func doSomething() {

        print("Doing something")

    }

}


func makeInstance() -> some SomeProtocol {

    return ConcreteType()

}


Here, the makeInstance() function returns some SomeProtocol - an opaque type conforming to SomeProtocol. The caller doesn't know or need to know the concrete type behind it. Opaque types provide a few key benefits: - They hide implementation details while still guaranteeing the returned type conforms to the protocol - They allow more flexibility to change the underlying concrete type in the future - They enhance code organization by separating the protocol from concrete type definitions The any Keyword and Type Erasure While some abstracts away the concrete type on the return type, any does the same within collections. The any keyword allows creating a type-erased wrapper around a protocol so you can work with protocol instances without knowing their concrete types.

protocol SomeProtocol {

    func doSomething()

}


struct ConcreteType1: SomeProtocol { ... }

struct ConcreteType2: SomeProtocol { ... }


let instances: [any SomeProtocol] = [ConcreteType1(), ConcreteType2()]


for instance in instances {

    instance.doSomething()

}


Here, the instances array contains elements conforming to SomeProtocol, with their concrete types (ConcreteType1 and ConcreteType2) being type-erased and wrapped in any SomeProtocol. This can be invaluable when you want to store heterogeneous collections of protocol-conforming instances without caring about their concrete types. When to Use some vs any In general, use some when you want to return an opaque type conforming to a protocol from a function. Use any when you want to store heterogeneous collections of protocol instances. Both features allow abstracting away concrete types, making your code more flexible and maintainable. While a bit more complexity up front, the benefits of code organization and abstraction make some and any powerful additions to the Swift language.
Previous
Next Post »

BOOK OF THE DAY