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?

Larme
  • 24,190
  • 6
  • 51
  • 81
ma11hew28
  • 121,420
  • 116
  • 450
  • 651

1 Answers1

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"
Papershine
  • 4,995
  • 2
  • 24
  • 48