Hello everyone, I am a swift beginner, and here is a problem I have:
example code like this:
struct Cat<T> {
let food: T
let eat: (T) -> ()
let size: Int
}
// all cats eat their own food in order
func feed<T>(cats: Cat<T>...) {
let orders = cats.indices.sorted(by: { i, j in cats[i].size > cats[j].size })
for i in orders {
let cat = cats[i]
cat.eat(cat.food)
}
}
But the feed
function can only deal with one kind of Cat
s, actually I want do things like this:
typealias Cats2<A, B> = (Cat<A>, Cat<B>)
func feed<A, B>(cats: Cats2<A, B>) {
if cats.0.size > cats.1.size {
cats.0.eat(cats.0.food)
cats.1.eat(cats.1.food)
} else {
cats.1.eat(cats.1.food)
cats.0.eat(cats.0.food)
}
}
It's impossible to write down all cases:
typealias Cats3<A, B, C> = (Cat<A>, Cat<B>, Cat<C>)
typealias Cats4<A, B, C, D> = (Cat<A>, Cat<B>, Cat<C>, Cat<D>)
func feed<A, B, C>(cats: Cats3<A, B, C>) {
}
func feed<A, B, C, D>(cats: Cats4<A, B, C, D>) {
}
Is there a way I can do to achieve this: func feed(cats: Cat...)
which accept various types of <T>
?