在 swift 函数中使用数组中的单个 ckrecords 时出现问题
Trouble using individual ckrecords from array in swift function
我正在尝试调用函数 addBoundry(CLLocation),但出现错误 "Type [CKRecord] has no subscript member"。如何分别为每条记录调用函数。
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])
}
}
}
}
我认为您输入错误的问题中的错误消息。
您几乎可以肯定实际遇到的错误是:
Type '[CKRecord]?' has no subscript members
您的问题的线索在错误消息中。 ?
表示您有一个数组 Optional,在这种情况下您需要解包。
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 风格的 for 循环。还有一种更简单的方法(在 Swift 的两个版本中)循环记录:
for record in records {
// do something with each record
}
我正在尝试调用函数 addBoundry(CLLocation),但出现错误 "Type [CKRecord] has no subscript member"。如何分别为每条记录调用函数。
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])
}
}
}
}
我认为您输入错误的问题中的错误消息。
您几乎可以肯定实际遇到的错误是:
Type '[CKRecord]?' has no subscript members
您的问题的线索在错误消息中。 ?
表示您有一个数组 Optional,在这种情况下您需要解包。
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 风格的 for 循环。还有一种更简单的方法(在 Swift 的两个版本中)循环记录:
for record in records {
// do something with each record
}