我不确定为什么Swift无法推断出我明确传入的类型,作为参数。
在下面的抓取管理器中,当我尝试加载“实体”类型的对象时,出现错误。
泛型参数'实体'无法推断
class EventsViewController: UIViewController {
private let fetchManager = FetchManager()
override func viewDidLoad() {
super.viewDidLoad()
fetchManager.willPerformQuery = {}
// generic parameter 'Entity' could not be inferred
fetchManager.loadObjects(ofType: Event) { (outcome) in
switch outcome {
case .success(let events):
print("Entities: \(events.count)")
case .failure(let code):
switch code {
case .connectionUnavailable:
print("1")
case .notAuthenticated:
print("2")
case .retry:
print("3")
case .serviceUnavailable:
print("4")
case .unknown:
print("5")
}
}
}
}
}
class FetchManager {
private let database: ReadableDatabase = CloudKitDatabase()
var willPerformQuery: () -> Void = {}
func loadObjects<Entity: Queryable & CloudKitInitable>(ofType type: Entity, withCompletion completion: @escaping (FetchOutcome<Entity>) -> Void) {
database.loadObjects(matching: Entity.query, willPerformQuery: { [weak self] (_) in
self?.willPerformQuery()
}, didPerformQuery: { (outcome) in
switch outcome {
case .success(let files):
let entities: [Entity] = files.compactMap(Entity.init)
completion(FetchOutcome<Entity>.success(entities))
case .failure(let code):
completion(FetchOutcome<Entity>.failure(code))
}
})
}
}
答案 0 :(得分:0)
引用类型本身(访问其“元类型”)的语法是TypeName.self
。在这种情况下,您将使用Event.self
:
fetchManager.loadObjects(ofType: Event.self) { (outcome) in
^~~~~
方法签名也应该使用Entity.Type
进行更新,因此编译器可以告诉它需要类型information
而不是类型instance
:
func loadObjects<Entity: Queryable & CloudKitInitable>(ofType type: Entity.Type, ...) {
...
}