我试图创建一个包含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()
}
}
答案 0 :(得分:0)
public func getGenericType() -> T.Type {
return T.self
}
答案 1 :(得分:0)
该错误消息表示它的意思。仅符合Codable并不能保证init
存在,因此说T()
是非法的。您必须自己做出保证。例如:
protocol CodableAndInitializable : Codable {
init()
}
class ResponseBase: Codable {
// ....
}
class Response<T: CodableAndInitializable>: ResponseBase {
var data: T?
// ....
public func getGenericType() -> Codable {
return T()
}
}