Accessing subclass members using KeyPath

232 Views Asked by At

I was trying to access subclass members using KeyPath when I encountered something strange. Look at these 2 simple classes:

class A {
    var a:String {
        get {
            return "str"
        }
    }
}

class B: A {
    override var a:String {
        get {
            return "str1"
        }
    }

    var c = 10
}

Now if I have the following code:

var m: A = B()
var k = \B.a
print(m[keyPath: k])

I will get a runtime error. It seems that you cannot access to subclass members using a WriteableKeyPath. But the following code works:

var m: A = B()
var k: AnyKeyPath = \B.a
print(m[keyPath: k]!)

I can use this code to access both \B.a and \B.c. Any idea why it is like this?

Since returned object by using AnyKeyPath is immutable, I will not be able to use it for updating object. I wonder if there is any workaround for updating subclass members using a KeyPath on parent class or not.

Update:

In order to elaborate more, here is another example:

var v: UIView = UILabel()
var k = \UILabel.text
v[keyPath: k] = "test" // Error cannot do this

I think this can be very useful.

0

There are 0 best solutions below