协议是swift中的一种类型,应该作为一种类型在任何地方使用,所以为什么协议组合不能在swift中的struct中使用?
protocol Named {
var name: String { get }
}
protocol Aged {
var age: Int { get }
}
struct Person: Named, Aged {
var name: String
var age: Int
}
func wishHappyBirthday(to celebrator: Named & Aged) {
print("Happy birthday, \(celebrator.name), you're \(celebrator.age)!")
}
let birthdayPerson = Person(name: "Malcolm", age: 21)
wishHappyBirthday(to: birthdayPerson)
// Prints "Happy birthday, Malcolm, you're 21!"
在 struct Person 中,如果我将其更改为
struct Person: Named & Aged {
var name: String
var age: Int
}
出现编译器错误:此处既不允许也不需要协议组合
那么为什么我可以在功能而不是 struct 中使用协议组合?