Swift: What’s the difference between some Book vs any Book?

KD Knowledge Diet
2 min readApr 15, 2024

--

In Swift, the `any` and `some` keywords are used in different contexts to refer to types, and they have distinct meanings and usage scenarios.

  1. `any Book`:
  • The `any` keyword is used to define an existential type. It allows you to create a variable or parameter that can hold values of different types that conform to a common protocol or meet certain requirements.
  • When you use `any` with a protocol or type, you are essentially saying that the variable can hold any value that conforms to that protocol or type.
  • Example: Suppose you have a protocol called `Readable` that represents objects that can be read. You can define a variable of type `any Readable`, which can hold any object conforming to the `Readable` protocol, regardless of the specific types.
var myReadable: any Readable

You can assign any value that conforms to the `Readable` protocol to `myReadable`, like this:

myReadable = Book()
myReadable = Magazine()

In this case, both `Book` and `Magazine` conform to the `Readable` protocol, so you can assign instances of both types to `myReadable`.

2. `some Book`:

  • The `some` keyword is used to define an opaque type or a specific type that the compiler infers based on context. It is primarily used for return types of functions and properties.
  • When you use `some` in a function’s return type or a property’s type, you are indicating that the actual type returned will be determined by the specific implementation but will always conform to the specified protocol or type.
  • Example: Suppose you have a function `getBook` that returns a value conforming to the `Book` type.
func getBook() -> some Book {
return Book()
}

In this case, you’re telling the compiler that `getBook` returns something of type `Book`, but you don’t need to specify the exact concrete type. The compiler infers it based on the implementation. You can use this feature to abstract the concrete types from the caller.

let someBook = getBook()

Here, `someBook` is of type `Book`, but you didn’t explicitly specify it in the function’s return type.

In summary, the key difference between `any Book` and `some Book` is that `any` is used to define existential types that can hold any value conforming to a protocol or type, while `some` is used to define opaque types where the compiler infers the specific type based on the context, ensuring it conforms to the specified protocol or type.

--

--

KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!