Swift 映射数组意外参数类型
Swift map array unexpected argument type
我有以下带有地图的代码,为什么 log
也是一个数组而不只是一个 CKRecord
对象?
sharedDatabase.perform(query, inZoneWith: nil) { (records, error) in
if let error = error {
reject("there is error", "no logs", error)
}else{
NSLog("found results")
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let resultLogs = records.map { log in
// Log is also an array: [CKRecorder] so I'll get error:
// Value of type '[CKRecord]' has no member 'object'
return [
"log": log.object(forKey: "log") ?? "N/A" as __CKRecordObjCValue,
"createdAt": formatter.string(from: log.creationDate ?? Date.init())
]
}
resolve(resultLogs)
}
Because the map
function also exists on Optional
。请注意 records
后缺少 ?
。您可能想先将它解包在 guard
中,或者添加 ?
以在整个表达式上使用可选链接。
当您使用 return 一个可选值和一个可选错误的完成处理程序时,您应该始终可选地绑定该值,同时检查错误是否为 nil
。这将解决您尝试调用 Optional
的 map
而不是 Array
.
的问题。
sharedDatabase.perform(query, inZoneWith: nil) { (records, error) in
guard let records = records, error == nil else {
return reject("there is error", "no logs", error!)
}
NSLog("found results")
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let resultLogs = records.map { log in
return [
"log": log.object(forKey: "log") ?? "N/A" as __CKRecordObjCValue,
"createdAt": formatter.string(from: log.creationDate ?? Date())
]
}
resolve(resultLogs)
}
我有以下带有地图的代码,为什么 log
也是一个数组而不只是一个 CKRecord
对象?
sharedDatabase.perform(query, inZoneWith: nil) { (records, error) in
if let error = error {
reject("there is error", "no logs", error)
}else{
NSLog("found results")
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let resultLogs = records.map { log in
// Log is also an array: [CKRecorder] so I'll get error:
// Value of type '[CKRecord]' has no member 'object'
return [
"log": log.object(forKey: "log") ?? "N/A" as __CKRecordObjCValue,
"createdAt": formatter.string(from: log.creationDate ?? Date.init())
]
}
resolve(resultLogs)
}
Because the map
function also exists on Optional
。请注意 records
后缺少 ?
。您可能想先将它解包在 guard
中,或者添加 ?
以在整个表达式上使用可选链接。
当您使用 return 一个可选值和一个可选错误的完成处理程序时,您应该始终可选地绑定该值,同时检查错误是否为 nil
。这将解决您尝试调用 Optional
的 map
而不是 Array
.
sharedDatabase.perform(query, inZoneWith: nil) { (records, error) in
guard let records = records, error == nil else {
return reject("there is error", "no logs", error!)
}
NSLog("found results")
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let resultLogs = records.map { log in
return [
"log": log.object(forKey: "log") ?? "N/A" as __CKRecordObjCValue,
"createdAt": formatter.string(from: log.creationDate ?? Date())
]
}
resolve(resultLogs)
}