Skip to content

Instantly share code, notes, and snippets.

@carlynorama
Created May 20, 2023 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlynorama/6417ff28c18b9d033807744c11e3d883 to your computer and use it in GitHub Desktop.
Save carlynorama/6417ff28c18b9d033807744c11e3d883 to your computer and use it in GitHub Desktop.
Some vs Any
protocol Vegetable {
var crunchy:Bool { get }
var volume:Int { get } //in mL
}
struct Carrot:Vegetable {
var volume: Int = 300
var crunchy = true
}
struct Celery:Vegetable {
var volume: Int = 300
var crunchy = true
}
struct Potato:Vegetable {
var volume: Int = 300
var crunchy = false
}
struct SoupFactory {
func receiveMixedProduce(delivery:[any Vegetable]) -> Int {
delivery.map { chop(item:$0) }.reduce(0, +)
}
func receiveSingleCrop(delivery:[some Vegetable]) -> Int {
delivery.map { chop(item:$0) }.reduce(0, +)
}
func chop(item: some Vegetable) -> Int {
item.volume
}
}
let factory = SoupFactory()
let howMuchSoup = factory.receiveMixedProduce(delivery: [Carrot(), Potato(), Celery()])
let howMuchSoup2 = factory.receiveSingleCrop(delivery: [Potato(), Potato(), Potato()])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment