获取一种变量并在Swift中声明此类型的其他变量

时间:2017-08-26 12:55:54

标签: json swift reflection types

我目前正在快速探索JSON世界,并且制作干净的代码时遇到了一些麻烦。

让我们说我有以下结构

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

我使用反射来获取标签的字典:使用此函数的此结构的值:

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
}

现在我有[String : AnyObject]的字典,问题就出现了。

我希望能够做到这样的事情

class JSONManager {

class func decode<T>(fromData data: Data) -> [T]? where T : JSONModelProtocol {
  let jsonObject = try? JSONSerialization.jsonObject(with: data,
                                                   options: [])

  guard let jsonDictionary = jsonObject as? [AnyObject] else {
    return nil
  }

  guard let json = jsonDictionary as? [[String : Any]] else {
    return nil
  }

  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
      // Same whit let type = type(of: value)
      let item = jsonItem[label] as? type // This line doesn't work I cannot cast here
    }
  }
}

有关如何实现这一点的想法吗?

0 个答案:

没有答案