我正在协议扩展中声明此方法
protocol Storable { ... }
extention Storable {
static func get<T: Decodable>(by identifier: String, completion: @escaping (T?) -> Void)
...
}
现在我在实现Storable
的类型上使用该方法。
struct User: Storable {
...
}
User.get(by: "userId", completion: { user in
print(user)
}
但是编译器说:Generic parameter 'T' could not be inferred
我想告诉编译器“ T是调用静态方法的类”
我成功使用:
进行编译static func get<T>(by identifier: String, type: T.Type, completion: @escaping (T?) -> Void) where T: Decodable
and
User.get(by: "mprot", type: User.self) { ... }
但是似乎多余:(
假设您仅在T是调用静态方法的类]时才应用get
,这是怎么回事?
protocol Storable { //... } extension Storable where Self: Decodable { static func get(by identifier: String, completion: @escaping (Self?) -> Void) { //... } } struct User: Storable, Decodable { //... }
这将成功编译:
User.get(by: "userId", completion: { user in
print(user)
})
T一定不是可选的。您应该具有: