Caleb Caleb - 6 months ago 49
iOS Question

Trouble using individual ckrecords from array in swift function

I am trying to call the function addBoundry(CLLocation), but get the error "Type [CKRecord] has no subscript member". How can I call the function for each record individually.

func loadLocation(completion: (error:NSError?, records:[CKRecord]?) -> Void)
let query = CKQuery(recordType: "Location", predicate: NSPredicate(value: true))
CKContainer.defaultContainer().publicCloudDatabase.performQuery(query, inZoneWithID: nil){
(records, error) in
if error != nil {
print("error fetching locations: \(error)")
completion(error: error, records: nil)
} else {
print("found locations: \(records)")
completion(error: nil, records: records)
for(var i = 0; i<records!.count; i += 1)


I believe you mistyped the error message in your question.

The error you were almost certainly actually getting was:

Type '[CKRecord]?' has no subscript members

And the clue to your problem is in the error message. The ? signifies that you have an array Optional, which in this case you need to unwrap.

guard let records = records else {
    // handle error in here
// after this point, `records` is a [CKRecord], not a [CKRecord]?

I would strongly suggest reading over the Swift Programming Language documentation on Optionals.

Also, I assume you are using Swift 2.x, because Swift 3 gets rid of C-style for loops. And there's an easier way (in both version of Swift) to loop over the records:

for record in records {
    // do something with each record