0

Is it possible to access an object's superclass's property using key-value coding?

I tried something like this:

class Bar: Foo {
    var shouldOverridePropertyOfFoo: Bool = false

    var propertyOfFoo: String {
        if shouldOverrideProperty {
            return "property of Bar"
        } else {
            return value(forKeyPath: "super.propertyOfFoo") as! String
        }
    }
}

But, I got this runtime error:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<MyModule.Bar 0x2da2cf003e00> valueForUndefinedKey:]: this class is not key value coding-compliant for the key super.'

Note: I'm trying to figure out how to override private method and call super in swift?

0

1 Answer 1

1

Instead of super.aPropertyOfFoo, you have to use Foo.aPropertyOfFoo, which is better done with #keyPaths instead of Strings:

class Foo: NSObject {
    @objc var aPropertyOfFoo = "property of foo"
}

class Bar: Foo {
    var shouldOverridePropertyOfFoo: Bool = false

    var propertyOfFoo: String {
        if shouldOverridePropertyOfFoo {
            return "property of bar"
        } else {
            return value(forKeyPath: #keyPath(Foo.aPropertyOfFoo)) as! String
        }
    }
}

let bar = Bar()
print(bar.propertyOfFoo) // "property of foo"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.