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
}
Error: Protocol 'Representable' can only be used as a generic constraint because it has Self or associated type requirements if 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
I believe what you're asking for is not possible, because RepresentType
remains unknown until a confirming class defines it.
Here are some related SO questions that deal with the same issue:
In Swift, how to cast to protocol with associated type?
why is this causing so much trouble? (protocols and typealiases on their associated types)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With