In swift5.x, I want to use a protocol named Animal with an associatedType 'T'.
class Shape {
func transform() {
print("Shape transofrm")
}
}
protocol Animal {
associatedtype T: Shape
var tansformT: T { get set }
func bark()
}
var a: any Animal
Rectangle
and Circle
implements the Shape
protocol:
class Rectangle: Shape {
override func transform() {
print("Rectangle transofrm")
}
}
class Circle: Shape {
override func transform() {
print("Circle transofrm")
}
}
And there are two class implements Animal
protocol:
class Dog : Animal {
var tansformT: Rectangle = Rectangle()
func bark() {
}
}
class Cat: Animal {
var tansformT = Circle()
func bark() {
print("Cat bark")
}
}
I want to declare a variable ani
, it can be Dog
or Cat
according the condition, so i try this:
var a = 10
var ani: Animal
if a == 10 {
ani = Cat()
} else {
ani = Dog()
}
then the compiler reports an error:
Protocol 'Animal' can only be used as a generic constraint because it has Self or associated type requirements
I have try my best for 3+ hours, I don't know how to solve it.