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? 具有代表性
重要的是每个类都实现其表示类型的枚举,但可以检查该类是否符合协议
我相信你所要求的是不可能的,因为RepresentType在确认类定义它之前仍然未知。
以下是处理同一问题的一些相关 SO 问题:
| 归档时间: |
|
| 查看次数: |
2105 次 |
| 最近记录: |