1

In the following example I expect the x.responds(to: Selector(name)) to return true. However it doesn't.

x.value(forKeyPath: name) throws a signal SIGABRT error.

The same code worked in Swift 3.

My question: how do I check for properties in a class (that extends from NSObject) and retrieve them based on a string.

import UIKit

class Test: NSObject {
    var test = "test"
}

func property(_ object: Any, _ name: String) -> Bool? {
    let x = object as? NSObject

//    x?.value(forKeyPath: name)

    return x?.responds(to: Selector(name))
}

property(Test(), "test")

(code for a playground in Swift 4.2)

user3703155
  • 76
  • 1
  • 7

1 Answers1

3

Placing @objc in front of var test fixed the issues.

import UIKit

class Test: NSObject {
    @objc var test = "test"
}

func property(_ object: Any, _ name: String) -> Bool? {
    let x = object as? NSObject

    x?.value(forKeyPath: name)

    return x?.responds(to: Selector(name))
}

property(Test(), "test")
user3703155
  • 76
  • 1
  • 7