【问题标题】:How to initialize stored property which is of type associatedtype protocol如何初始化关联类型协议类型的存储属性
【发布时间】: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


【解决方案1】:
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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多