【问题标题】:Generic types error : Cannot explicitly specialise a generic type泛型类型错误:无法显式特化泛型类型
【发布时间】:2017-05-19 07:42:01
【问题描述】:

我正在尝试在RequestManager 中创建一个通用函数,通过ServiceManager 将接收到的JSON 从服务器转换为指定的类型。这是我的代码:

RequestManager:

typealias ResultResponseManager  = (_ data: AnyObject?, _ error: ErrorPortage?) -> Void
typealias SuccessResponseManager = (_ success: Bool, _ error: ErrorPortage?) -> Void
typealias objectBlock<T:GenericModel> = (_ object: T?, _ error: ErrorPortage?) -> Void

extension RequestManager {

    static func getObject<T: GenericModel>(endpoint: String, completionBlock: objectBlock<T>? = nil){

        RequestHelper(url: "\(getAPIURL())\(endpoint))")
            .performJSONLaunchRequest { (result, error) in

                if let result = result as? NSDictionary,
                    error == nil {
                    let object = T(dic: result)
                    completionBlock?(object, nil)
                }
                else {
                    completionBlock?(nil, error)
                }
        }
    }


}

ServiceManger:

typealias ObjectResult =  (GenericModel?, ErrorPortage?) -> Void
typealias ObjectsResult =  ([GenericModel]?, ErrorPortage?) -> Void

extension ServiceManager {

    static func getUser(_ id: Int? = nil, _ completion: ObjectResult? = nil) {

        guard let userId: Int = id ?? UserManager.shared.userId else {

            return
        }

        RequestManager.getObject<User>(endpoint: "users/\(userId)") { (user, error) in
            if user = user {

                //update userdefault
                if userId == UserManager.shared.userId {
                    UserDefaults.standard.set(result, forKey: "currentUser")
                }
            }
        }
    }
}

在线RequestManager.getObject&lt;User&gt; ... 我收到此错误:

无法显式特化泛型类型

那么我在这里错过了什么?

感谢luk2302,问题解决了

更新 知道如何改进此代码或使其更干净! 注意:这不是问题,而是良好的编程习惯

【问题讨论】:

    标签: swift cocoa-touch generics swift3 protocols


    【解决方案1】:

    比较https://stackoverflow.com/a/35372990/2442804 - 您不能“手动”指定类型约束。你必须让编译器推断它。通过以下方式进行:

    RequestManager.getObject(endpoint: "users/\(userId)") { (user : User?, error) in 
        // ... your normal code
    

    【讨论】:

    • 谢谢 :) 你能检查一下我的更新吗(这只是为了拥有干净的代码,也许是为了更好地组织我的代码)
    • @Chlebta 我会选择一个带有 errorsuccess 案例相关值的枚举。这样,您就有了一种编译器强制的方式来接收错误信息或实际对象。 SO上有几篇关于这个的帖子(现在找不到它们),对于评论部分来说,更详细的内容太多了。除了枚举之外,我认为您的代码很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    相关资源
    最近更新 更多