samedi 26 août 2017

Get a type of variable and declare an other variable with this type in Swift

I currently exploring the JSON world in swift and I've some trouble to make a clean code.

Let's say I've the following structure

struct Foo {
  var a: String = ""
  var b: Int = 0
}

I use reflection to get a dictionary of the label : value of this struct with this function:

static func dictionaryRepresentation() -> [String : AnyObject] {
  var dictionnary = [String : AnyObject]()

  for child in Mirror(reflecting: self).children {
    dictionnary[child.label!] = child.value as AnyObject
  }

  return dictionnary
}

Now I have a dictionary of [String : AnyObject] and here comes the issue.

I would like to be able to do something like this

let representation = T.dictionaryRepresentation()
for jsonItem in json { // json is a dictionary [String : Any]
  for (label, value) in object {
    let type = Mirror.init(reflecting: value).subjectType // The type of the item
    let item = jsonItem[label] as? type // This line doesn't work I cannot cast here
  }
}

Any idea about how to achieve this?





Aucun commentaire:

Enregistrer un commentaire