protocol Identifiable {
associatedtype ID
func identifier() -> ID
}
protocol PersonProtocol: Identifiable {
var name: String { get }
var age: Int { get }
}
class Person: PersonProtocol {
let name: String
let age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func identifier() -> String {
return "\(name)_\(age)"
}
}
我试图在类let owner: PersonProtocol
中声明并初始化存储的属性为Car
,但它给出了一个错误:
`PersonProtocol'只能用作一般约束,因为它具有Self或关联的类型要求
因此,我尝试按照以下代码执行相同的操作,但是我不确定这是否是正确的方法。需要建议。
class Car<T: PersonProtocol>{
let owner: T
init<U: PersonProtocol>(owner: U) where U.ID == String {
self.owner = owner as! T // I am force casting `U` as `T`. is this forcecasting justified ?
}
func getID() -> String {
owner.identifier() as! String // is this forcecasting justified ?
}
}
class Car<U,T: PersonProtocol> where T.ID == U{
let owner: T
init(owner: T) {
self.owner = owner
}
func getID() -> U {
owner.identifier()
}
}
let person = Person(name: "John Snow", age: 34)
let car = Car<String, Person>(owner: person)