I have the following code with a map, why is the log
also an array instead of just a CKRecord
object?
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)
}
When you work with completion handlers that return an Optional value and an Optional error, you should always optional bind the value while checking if the error is nil
or not. This will solve your issue caused by the fact that the you're trying to call Optional
's map
instead of that of 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)
}