如何初始化关联类型协议类型的存储属性

问题描述 投票:0回答:1
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或关联的类型要求

enter image description here因此,我尝试按照以下代码执行相同的操作,但是我不确定这是否是正确的方法。需要建议。

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
1个回答
0
投票
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)

© www.soinside.com 2019 - 2024. All rights reserved.