2

Consider the following protocol:

@objc protocol P {
    init()
    optional var t: Int { get set }
}

If I try to interact with t in this class

class C<T: P>: NSObject, P {
    required override init() { }
    lazy var p: P = {
        return T()
    }()
    var t: Int {
        set {
            p.t = newValue // cannot assign to property: 'self' is immutable
        }
        get {
            return p.t ?? 0 // interestingly, `t` is typed as Optional<Int> here
        }
    }
}

I get the error "cannot assign to property: 'self' is immutable.

It seems to me that the real problem is that swift doesn't know if p actually implements t.

I've tried calling respondsToSelector, but that can't refer to a property, apparently, and even if it was allowed, I don't know if it would actually be enough to prove to the compiler that this was legitimate. Google/searching SO is made more difficult by the fact that "Optional" is a type as well as a keyword in swift. I've also considered a number of workarounds for the specific case this question was inspired by, but I would like to know how to actually call the method from swift.

How do I check that p implements t in a way that will satisfy the compiler?

Ben Pious
  • 4,765
  • 2
  • 22
  • 34

0 Answers0