首页 文章

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

提问于
浏览
2

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

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
}

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

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

1 回答

相关问题