简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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