I have to following class type
class Recipe {
private let id: CKRecord.ID
let name: String
let coverPhoto: CKAsset?
init?(record: CKRecord, database: CKDatabase) {
guard
let name = record["name"] as? String
else { return nil }
id = record.recordID
self.name = name
coverPhoto = record["coverPhoto"] as? CKAsset
}
and in my viewcontroller, I want to display list of names that I fetched from cloudkit. So, i am trying to find a way to convert CKRecord to my class type Recipe.
I tried this but failed
let query = CKQuery(recordType: "GroceryItem", predicate: NSPredicate(value:true))
database.perform(query, inZoneWith: nil) { [weak self] records, error in
guard let records = records,error == nil else {
return
}
DispatchQueue.main.async {
self?.items = records.compactMap({ $0.value as? Recipe }) // gives error ambigous value
self?.tableView.reloadData()
}
}
Records is the fetched variable from cloudkit as CKRecord
items is array of Recipe, [Recipe]
I want to transfer the data from records to items.
You cannot cast the type. You have to call init
.
First remove the database
parameter from the init method, it’s obviously not needed
init?(record: CKRecord) { …
Then replace
self?.items = records.compactMap({ $0.value as? Recipe })
with
self?.items = records.compactMap(Recipe.init)