TruMan1
TruMan1

Reputation: 36058

Adding protocol conformance to existing class then checking if implements?

I'm trying to group a couple of existing classes into a single custom protocol so I can treat them the same. For example, I'd like to group these two classes together under a single protocol like this:

protocol CLKComplicationTemplateRingable {
    var fillFraction: Float { get set }
}

extension CLKComplicationTemplateCircularSmallRingText: CLKComplicationTemplateRingable {

}

extension CLKComplicationTemplateModularSmallRingText: CLKComplicationTemplateRingable {

}

How come when I do this, I cannot do this:

if let template as? CLKComplicationTemplateRingable {
    print("\(template.fillFraction)")
}

It doesn't compile, it gives this error: Variable binding in a condition requires an initializer

Am I approaching this correctly? Any advise or help would be greatly appreciated!

Upvotes: 0

Views: 158

Answers (1)

Darko
Darko

Reputation: 9845

Do it like this:

if template is CLKComplicationTemplateRingable {
    print("\(template.fillFraction)")
}

The "if let" variant would be:

if let template = template as? CLKComplicationTemplateRingable {
    print("\(template.fillFraction)")
}

Upvotes: 1

Related Questions