1

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))
Blackbeard
  • 652
  • 2
  • 8
  • 22
  • 1
    Did you try overriding `responds(to:)`? – matt Jan 31 '18 at 14:52
  • 1
    Selectors are case-sensitive. `allUsers` is different from `allusers`, so you are asking if you can check if an object responds to selector A by asking about selector B. You could use the Objective C runtime to do this check, but you shouldn't, and it won't be easy nor worth it. – EmilioPelaez Jan 31 '18 at 15:02
  • You could convert the dictionary keys to camel case. Though you might need some advanced heuristics to make it right. Alternatively you could map the keys from the push notifications to their camel case variant. – Cristik Jan 31 '18 at 19:53
  • You could enumerate properties like here https://stackoverflow.com/a/24845527/5329717 and combine in with Caleb's approach – Kamil.S Feb 10 '18 at 22:00

1 Answers1

0

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.

Caleb
  • 124,013
  • 19
  • 183
  • 272