vendredi 9 août 2019

In Swift iterate a blind struct .... but modify the values?

struct Thing: Codable {
  let a: String
  let b: Int
  let c: String
  let d: Int
}

and

var x: Thing

We want to set all the Strings in x to "666"

// set all strings to "666"
x.a = "666"
x.c = "666"
// all done

But wait, some other programmer has added new fields to Thing

  let e: Int
  let f: String
  let g: String

Is there any general code like

 for let type(of: field) in x = String.self {
    x.field = "666"
 }

?

It's easy enough to find all the Stringy fields

for (n, v) in Mirror(reflecting: x).children {
    print("try all these \(n) \(v)")
    if type(of: v) == String.self {
        print(" booyah, that one is String")
    }
}

But I don't know of a way to get to a field in an object, from, the Mirror iteration.

(Can you perhaps just access struct fields .... by index?!)

Is there a way to

set all the String fields in a struct instance to "666" ?

.. perhaps once you've got them all via Mirror?





Aucun commentaire:

Enregistrer un commentaire