非标称类型 'T' 不支持显式初始化 Codable

Non-nominal type 'T' does not support explicit initialization Codable

我正在尝试创建一个包含 API 请求的响应库,但在使用 codable 时出现错误 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()
    }
}
public func getGenericType() -> T.Type {
    return T.self
}

错误信息就是它所说的意思。仅仅符合 Codable 并不能保证 init 存在,所以说 T() 是非法的。你必须自己做出保证。例如:

protocol CodableAndInitializable : Codable {
    init()
}
class ResponseBase: Codable {
    // ....
}
class Response<T: CodableAndInitializable>: ResponseBase {
    var data: T?
    // ....
    public func getGenericType() -> Codable {
        return T()
    }
}