简体   繁体   English

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

[英]How to implement conditional conformance of a generic to a protocol in a function?

I have a basic networking function in swift as given below: 我迅速提供了基本的联网功能,如下所示:

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()
}

I would like to make the generic confirm to decodable protocol conditionally. 我想有条件地对可解码协议进行通用确认。 It should return the object when the when generic confirms to Decodable and return the json serialized object when it doesn't. 当when泛型确认为Decodable时,它应该返回该对象,否则返回json序列化的对象。 Something like below: 如下所示:

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()
}

How would I write a common function for both scenario? 如何为这两种情况编写通用函数?

I've been experimenting some runtime type conformance checking that may be useful. 我一直在尝试一些可能有用的运行时类型一致性检查。

1. 1。

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

2. 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")}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM