麻烦在swift函数中使用数组中的单个ckrecords

时间:2016-09-01 19:14:10

标签: ios swift function cllocationmanager cloudkit

我试图调用函数addBoundry(CLLocation),但得到错误"类型[CKRecord]没有下标成员"。如何单独为每条记录调用该函数。

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)
                {
                    addBoundry(records[i])
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

我相信您错误地输入了问题中的错误消息。

你几乎肯定得到的错误是:

  

Type '[CKRecord]?' has no subscript members

您的问题的线索在错误消息中。 ?表示您有一个数组可选,在这种情况下您需要解包。

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

我强烈建议阅读Swift Programming Language documentation on Optionals

另外,我假设你使用的是Swift 2.x,因为Swift 3摆脱了C风格的循环。并且有一种更简单的方法(在两个版本的Swift中)循环记录:

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