Maciej Trybiło
Maciej Trybiło

Reputation: 1207

Protocol downcasting in Swift

I have the following situation where I have a generic protocol A that can have variants that inherit from it (e.g. B) and a class that implements a variant (C).

protocol A {}

protocol B: A {
  var foo: String { get }
}

class C: B {
  let foo: String = "foo"
}

Now, if I have an object of type A, but is actually a C, how can I get to stuff declared in B?

func foo() {
  let c: A = C()
}

If I try to cast as in let b = c as B I get Cannot downcast from 'A' to non-@objc protocol type 'B'.

Upvotes: 2

Views: 507

Answers (1)

Antonio
Antonio

Reputation: 72760

Your code looks good - the only problem is that the as operator requires objc compatibility. You can fix it by prefixing your protocols with the @objc attribute:

@objc protocol A {}

@objc protocol B: A {
    var foo: String { get }
}

Unfortunately there's a downside on doing that: you lose the ability to use swift-specific features that are not available in objective C, such as enums, tuples, generics, etc.

More info here: Checking for Protocol Conformance

Upvotes: 2

Related Questions