如何使用 Swift 中的调用者类型推断静态泛型方法中的类型
How to infer type in static generic method with the type of the caller in Swift
我在协议扩展上声明此方法
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是调用静态方法的class”
我编译成功:
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 is the class who calls the static method"
假设您只想在 T 是调用静态方法的 class 时应用您的 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 不能是可选的。你应该有:
static func get<T: Decodable>(by identifier: String, completion: @escaping (T) -> ())
被调用
User.get(by: "userId", completion: { (value: User) in ... })
我在协议扩展上声明此方法
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是调用静态方法的class”
我编译成功:
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 is the class who calls the static method"
假设您只想在 T 是调用静态方法的 class 时应用您的 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 不能是可选的。你应该有:
static func get<T: Decodable>(by identifier: String, completion: @escaping (T) -> ())
被调用
User.get(by: "userId", completion: { (value: User) in ... })