0

I am working on a Swift service that stores codable types in JSON. The type also defines a nested CodingKeys enum to define the property names when coded to JSON. For example, I might have a type that looks like this:

struct MyType : Codable {
  let myIntProperty: Int
  let myStringProperty: String

  enum CodingKeys: String, CodingKey {
    case myIntProperty = "int_property"
    case myStringProperty = "string_property"
  }
}

Now I have a function that wants to operate on one of these properties, as specified by a key path to that property. Using the type from the example, I want a function that can be called like this:

 let result = myFunc(usingProperty: \MyType.myIntProperty)

My function is declared using the KeyPath type:

func myFunc<T: Codable, G>(usingProperty: KeyPath<T, G>) -> G {
  ...
}

In order to implement my function, I would like to somehow get access to not just the key path parameter named usingProperty, but also to the coding key that it is associated with. So when called with the key path to the myIntProperty property, I would want to get the name used when encoding it, which is int_property.

Is there any way to derive this value from the KeyPath parameter and its root type's CodingKeys enumeration?

Tim Dean
  • 8,253
  • 2
  • 32
  • 59
  • Why would you need to get something that you know already what it is? – Leo Dabus Feb 16 '22 at 03:02
  • @LeoDabus the function that needs it does NOT know what it is. It needs both the key path (to operate on the Codable objects) and the encoded name (to operate on the associated JSON) – Tim Dean Feb 16 '22 at 03:07
  • maybe you will use mirror to convert your object to dictionary so you can access to the property that you want. – cristian_064 Feb 16 '22 at 03:37
  • @TimDean this might help [Can Swift convert a class / struct data into dictionary?](https://stackoverflow.com/a/46597941/2303865) – Leo Dabus Feb 16 '22 at 03:55
  • Thanks @LeoDabus but that link only seems to provide an elegant place to put the code I need (in an extension to Codable) but doesn't provide anything to help me figure out what code I need to write. – Tim Dean Feb 16 '22 at 20:07
  • @TimDean No body can guess if you don't add a practical example of what you are trying to achieve. Again you shouldn't need the keys. Why do you think CodingKeys are private when it is automatically synthesized by a struct? – Leo Dabus Feb 16 '22 at 20:12
  • @LeoDabus - Sorry, but I guess I don't understand what is missing from my question. The practical example is right there in the question. Not sure what you mean when you suggest I think "CodingKeys are private" – Tim Dean Feb 16 '22 at 21:50
  • @TimDean I suggest forget about keypath and use a dictionary. Codable won't help IMO. But you can use the protocol if you want as shown in that post – Leo Dabus Feb 16 '22 at 22:23

0 Answers0