如何在函数中实现泛型对协议的条件一致性?

时间:2018-06-20 23:16:29

标签: json swift generics decodable

我迅速地具有基本的联网功能,如下所示:

func fetchObject<T: Decodable>(from url: URL, completion: @escaping (T) -> ()) {

    URLSession.shared.dataTask(with: url) { (data, _, _) in

        guard let data = data else { return }

        if let object = try? JSONDecoder().decode(T.self, from: data) {
            completion(object)
        }
    }.resume()
}

我想让泛型有条件地确认为可解码协议。当when泛型确认为Decodable时,它应该返回该对象,否则返回json序列化的对象。如下所示:

func fetchObject(from url: URL, completion: @escaping (Any) -> ()) {

    URLSession.shared.dataTask(with: url) { (data, _, _) in

        guard let data = data else { return }

        if let object = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves) {
            completion(object)
        }
    }.resume()
}

我如何为这两种情况编写一个通用函数?

1 个答案:

答案 0 :(得分:0)

我一直在尝试一些可能有用的运行时类型一致性检查。

1。

if let _ = object.self as? Decodable.Type {
                    print("\(object) conforms")
                }else {
                    print("\(object) does not conform")
                }

2。

        guard let data = data else { return }
           let myType = type(of: data)
           if myType.self == Decodable.Type.self {
                print("it's conforming")
            }else 
                {print ("it's not conforming")}