【发布时间】:2020-02-29 06:37:30
【问题描述】:
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)"
}
}
我尝试在Car 类中将存储属性声明和初始化为let owner: PersonProtocol,但它给出了错误:
`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 ?
}
}
【问题讨论】:
标签: swift generics swift-protocols associated-types