使用 Swift 中的关联类型检查是否符合协议

Ser*_*yev 5 protocols confirmation swift swift4

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

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
}
Run Code Online (Sandbox Code Playgroud)

错误:协议 'Representable' 只能用作通用约束,因为如果 let obj = obj as? 具有代表性

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

Ger*_*eon 1

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

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

在 Swift 中,如何转换为关联类型的协议?

为什么这会造成这么多麻烦?(相关类型的协议和类型别名)