问题描述
在类似情况下,如何检查对象是否符合可表示"协议?
How can I do a check object conforms to protocol 'Representable' in a similar situation?
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
}
错误:协议可表示"只能用作通用约束,因为它具有 Self 或关联的类型要求如果让 obj = obj as?具有代表性
Error: Protocol 'Representable' can only be used as a generic constraint because it has Self or associated type requirementsif let obj = obj as? Representable
重要的是每个类都实现其表示类型的枚举,但可以检查该类是否符合协议
It is important that each class implements its enumeration of types of representation, but the class can be checked of conforms to protocol
推荐答案
我相信您的要求是不可能的,因为 RepresentType
在确认类定义它之前仍然未知.
I believe what you're asking for is not possible, because RepresentType
remains unknown until a confirming class defines it.
以下是一些处理同一问题的相关 SO 问题:
Here are some related SO questions that deal with the same issue:
这篇关于使用 Swift 中的关联类型检查是否符合协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!