在Swift中检查conocol协议与关联类型

时间:2017-11-10 19:51:24

标签: swift protocols swift4 confirmation

如何使检查对象符合协议'可代表'在类似的情况下?

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
}

错误:协议&#39;可代表&#39;只能用作通用约束,因为它具有Self或关联类型要求 如果让obj = obj为?可表示的

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

1 个答案:

答案 0 :(得分: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)