【问题标题】:How to create a tuple containing an object that conforms to a protocol?如何创建包含符合协议的对象的元组?
【发布时间】:2019-08-28 04:15:28
【问题描述】:

假设我想使用 JSON 资源测试一堆类型的序列化:

let bundle = Bundle(for: type(of: self))
let decoder = JSONDecoder()

let tests : [(filename: String, type: ???)] = [
    ("Employee", Employee.self),
    ("Job", Job.self)
]
for test in tests {
    let filename = test.filename
    let type = test.type

    guard let url = bundle.url(forResource: filename, withExtension: "json") else {
        XCTFail("Failed to load file: \(filename).json")
        return
    }
    do {
        let data = try Data(contentsOf: url)
        let json = try JSONSerialization.jsonObject(with: data, options: [])
        let obj = try decoder.decode(type, from: data)
    }
}

test 元组应该如何声明?

【问题讨论】:

  • 是???占位符还是这只是我以前在 swift 中从未见过的东西?
  • 占位符。问题是那里有什么
  • 我认为这是不可能的。您必须在编译时提供要解码的类型。

标签: ios swift xcode generics tuples


【解决方案1】:

我会为此目的使用通用函数,请参见下面的示例:

//Model
struct Test: Decodable {
  var name: String
  var surname: String
  var gender: String
}


//Generic function
func readJsonData<T: Decodable>(filename: String, completion: @escaping (T) -> ()) {

   if let fileUrl = Bundle.main.url(forResource: filename, withExtension: "json") {
      do {

        let data = try Data(contentsOf: fileUrl)
        let decoder = JSONDecoder()
        let jsonData = try decoder.decode(T.self, from: data)
        completion(jsonData)

      } catch {
        print("error: \(error)")
      }
   }

   return
}

//How to call the generic function 
readJsonData(filename: "Test") { (obj: Test) in
   //do something with your returned object of type Test
}

【讨论】:

  • @GoldenJoe 你的三个问号 (???) 将被替换为 Any 甚至更好的 Decodable
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-02
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多