首页 > 解决方案 > 非标称类型 'T' 不支持显式初始化 Codable

问题描述

我正在尝试创建一个响应库来包含 API 请求,但Non-nominal type 'T' does not support explicit initialization在使用可编码时出现错误。这曾经与第三方库一起使用,但我正在将旧数据换成新数据。

class ResponseBase: Codable {
    var status: String?
    var message: String?
    var pagination: Pagination?

    var isSucessful: Bool {
        return status == "success"
    }

    struct ErrorMessage {
        static let passwordInvalid = " Current password is invalid."
        static let loginErrorIncorrectInfo = " Incorrect username/password."
        static let loginErrorAccountNotExist = " Invalid request"
    }
}

class Response<T: Codable>: ResponseBase {
    var data: T?

    public func setGenericValue(_ value: AnyObject!, forUndefinedKey key: String) {
        switch key {
        case "data":
            data = value as? T
        default:
            print("---> setGenericValue '\(value)' forUndefinedKey '\(key)' should be handled.")
        }
    }

    public func getGenericType() -> Codable {
        return T()
    }
}

标签: iosswiftcodable

解决方案


public func getGenericType() -> T.Type {
    return T.self
}

推荐阅读