Generic completion handler in Swift

試著忘記壹切 提交于 2019-12-03 21:43:26

The solution is to move the generic type up into the JSONRequest class - that way JSONCompletionHandler can be defined with the generic type you're requesting instead of just the Entity protocol. (Some of your code seemed a little pseudo-, so this might need some tweaking to fit back into your implementation.)

JSONRequest is now a generic class with an Entity type restraint:

public class JSONRequest<T: Entity>: Request {
    // completion handler defined in terms of `T`
    public typealias JSONCompletionHandler = ([T]?, NSError?) -> Void

    // no further changes        
    public var completionHandler: JSONCompletionHandler
    public var endPoint: String
    public init(endPoint: String, completionHandler: JSONCompletionHandler) {
        self.endPoint = endPoint
        self.completionHandler = completionHandler
    }
}

performJSONRequest doesn't need the type passed as a separate parameter any more. Since jsonRequest is specialized, it gets the type information from that parameter:

public func performJSONRequest<T: Entity>(jsonRequest: JSONRequest<T>) {
    // create array of `T` somehow 
    var entities: [T] = []
    var error: NSError?

    // completionHandler expects [T]? and NSError?
    jsonRequest.completionHandler(entities, error)
}

When creating your JSONRequest instance, the type given in the completion handler (e.g., [Book]?) will set the type for the generic JSONRequest, and hold throughout the process:

var request = JSONRequest(endPoint: "books") { (books: [Book]?, error) in
    println(books?.count)
}
performJSONRequest(request)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!