Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking conforms protocol with associatedtype in Swift

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

like image 792
Sergey Sergeyev Avatar asked Nov 08 '22 14:11

Sergey Sergeyev


1 Answers

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)

like image 146
Gereon Avatar answered Nov 24 '22 08:11

Gereon