从字面上来理解,就是相关类型。意思也就是被
associatedtype关键字修饰的变量,相当于一个占位符,而不能表示具体的类型。具体的类型需要让实现的类来指定。
protocol Food { }
protocol Animal {
    func eat(_ food: Food)
}
struct Meat: Food { }
struct Lion: Animal {
    func eat(_ food: Food) {
        if let meat = food as? Meat {
            print("eat \(meat)")
        } else {
            fatalError("Tiger can only eat meat!")
        }
    }
}
let meat = Meat()
Lion().eat(meat)
在实现中的转换很多时候并没有太多的意义,而且将责任扔给了运行时。好的做法是让编译的时候就确定Food的类型,这种情况就可以用associatedtype。
protocol Food {}
protocol Animal {
    associatedtype F: Food
    func eat(_ food: F)
}
struct Meat: Food {}
struct Lion: Animal {
    func eat(_ food: Meat) {
        print("eat \(food)")
    }
}
let meat = Meat()
Lion().eat(meat)
不过在添加 associatedtype 后,Animal 协议就不能被当作独立的类型使用了。这时候就需要使用泛型。
func isDangerous<T: Animal>(animal: T) -> Bool {
    if animal is Lion {
        return true
    } else {
        return false
    }
}