如何使检查对象符合协议'可代表'在类似的情况下?
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为?可表示的
每个类实现其表示类型的枚举非常重要,但可以检查类是否符合协议
答案 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)