在类似情况下,如何执行符合“可表示”协议的检查对象?
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”只能用作泛型约束,因为它具有自身或关联的类型要求
如果让obj=obj为?可代表的
每个类实现其表示类型的枚举是很重要的,但是可以检查该类是否符合协议
最佳答案
我相信你所要求的是不可能的,因为在确认类定义它之前,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)