some vs any in Swift

  • Holds a concrete type
  • Guarantees type relationship
  • Holds an arbitrary concrete type
  • Erases type relationship
some Animal<T: Animal>
func getValue<T>(Parameter) -> Result
let animal: some Animal = Horse()
let animal: some Animal = Horse()animal = Chicken() //ERROR, cannot assign value of type Chicken to type some Animal
func feed(_ animal: some Animal) {...}feed(Horse())feed(Chicken())
func makeView(for farm: Farm) -> some View {  FarmView(farm)}
@ViewBuilderfunc makeView(for farm: Farm) -> some View {  if condition {    FarmView(farm)  } else {    EmptyView()  }}
any Animal
[any Animal] maybe [Chicken(), Horse(), Cow(), Dog()] at runtime.
func feedAll(_ animals: [any Animal]) {  for animal in animals {    animal.eat(food: Animal.Feed) //ERROR, Associated type Feed can only be used with a concrete type  }}
struct Farm { func feed(_ animal: some Animal) {   let crop = type(of: animal).Feed.grow()   let produce = crop.harvest()   animal.eat(produce) } func feedAll(_ animals: [any Animal]) {   for animal in animals {     feed(animal)   } }}
protocol Animal {  associatedtype CommodityType: Food  func produce() -> CommodityType}
struct Farm {
var animals: [any Animal] func produceCommodities() -> [any Food] { return animals.map { animal in animal.produce() } }}
protocol Animal {  associatedtype FeedType: AnimalFeed  func eat(_: FeedType)}
struct Farm { var animals: [any Animal] func feedAll() { for animal in animals { animal.eat(???) //ERROR } }}
  • struct EditableMailmap: Mailmap
  • <Value: Mailmap>
  • where Element: Mailmap
  • some Mailmap
  • var map: any Mailmap
  • Array<any Mailmap>
  • where Element == any Mailmap
  • (any Mailmap) -> any Mailmap

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Taha Bebek

Taha Bebek

Senior Staff Software Engineer, iOS at Poshmark.