使用CloudKit
从CKRecord.ID
获取多种类型时,出现以下错误。
错误
Cannot invoke 'map' with an argument list of type '(@escaping (CKRecord.ID, String, CKAsset, Int) -> Lib)'
CloudKit提取功能
static func fetch(_ recordID: [CKRecord.ID], completion: @escaping (Result<[Lib], Error>) -> ()) {
let recordID: [CKRecord.ID] = recordID
let operation = CKFetchRecordsOperation(recordIDs: recordID)
operation.qualityOfService = .utility
operation.fetchRecordsCompletionBlock = { (record, err) in
guard let record = record?.values.map(Lib.init) ?? [] //returns error here
else {
if let err = err {
completion(.failure(err))
}
return
}
DispatchQueue.main.async {
completion(.success(record))
}
}
CKContainer.default().publicCloudDatabase.add(operation)
}
库
struct Lib {
var recordID: CKRecord.ID
var name: String
var asset: CKAsset
var rating: Int
}
如何使用CloudKit
从CKRecord.ID
检索多种类型?
答案 0 :(得分:1)
您尚未定义接受CKRecord
的初始化程序。
这将使其编译:
extension Lib {
init(_: CKRecord) { fatalError() }
}
摆脱?? []
,然后从那里走!
如果使用精确的复数形式可能会有所帮助:
operation.fetchRecordsCompletionBlock = { records, error in
guard let libs = records?.values.map(Lib.init)
答案 1 :(得分:0)
@Jessey的回答非常有帮助,但一直返回fatalError()
。最终起作用的是添加到init
中。
库
struct Lib {
var recordID: CKRecord.ID
var name: String
var asset: CKAsset
var rating: Int
init(record: CKRecord){
recordID = record.recordID
name = (record["name"] as? String)!
asset = (record["asset"] as? CKAsset)!
rating = (record["rating"] as? Int)!
}
}
“名称”,“资产”和“评级”是CloudKit仪表板记录中的自定义字段名称。我还按照指令去除了?? []
函数中的fetch
。