【问题标题】:Checking conforms protocol with associatedtype in Swift检查是否符合 Swift 中关联类型的协议
【发布时间】:2018-04-24 02:51:05
【问题描述】:

在类似情况下如何检查对象是否符合“可表示”协议?

protocol Representable {
    associatedtype RepresentType
    var representType: RepresentType { get set }
}

class A: UIView, Representable {
    enum RepresentType: String {
        case atype = "isa"
    }
    var representType: RepresentType = .atype
}

class B: UIView, Representable {
    enum RepresentType {
        case btype(value: String?)
    }
    var representType: RepresentType = .btype(value: nil)
}

let obj = A()
if let obj = obj as? Representable {  <<<<<<<<<<<< error
    obj.representType = A.RepresentType.atype
}

错误:协议“Representable”只能用作通用约束,因为它具有 Self 或关联的类型要求 如果让 obj = obj 为?有代表性的

每个类都实现其表示类型的枚举很重要,但可以检查该类是否符合协议

【问题讨论】:

    标签: swift protocols swift4 confirmation


    【解决方案1】:

    我相信您所要求的内容是不可能的,因为 RepresentType 在确认类定义它之前仍然未知。

    以下是一些处理同一问题的相关 SO 问题:

    In Swift, how to cast to protocol with associated type?

    why is this causing so much trouble? (protocols and typealiases on their associated types)

    【讨论】:

      猜你喜欢
      • 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
      相关资源
      最近更新 更多