Case-insensitive 'responds to selector' in Swift

220 Views Asked by At

I am getting some keys and values from a push notification. Then I want to check if the keys are properties of an object, so I can map the object accordingly. But I want to be able to use lower case keys and the object properties are camel-case.

So the question is how can man implement, in Swift 4, a case-insensitive version of NSObject's:

self.responds(to: Selector(value))
1

There are 1 best solutions below

0
Caleb On

But I want to be able to use lower case keys and the object properties are camel-case.

The problem here is that you lose information when you convert from camelCase to lowercase, so you can't easily convert in the other direction.

You'll need to build a dictionary that maps keys to selectors. Although Swift has some limited facilities for introspection, it's probably easiest to create the dictionary by hand and include only those properties that you want to participate in this process:

let properties : [String] = ["firstName", "lastName", "address", "zipCode"]
var map = [String:String]()
properties {
    map[$0.lowercased()] = $0
}

Now you can use map to find the property name for a given key.