尝试在函数中返回数组时收到的未解析的标识符

时间:2016-10-29 20:47:23

标签: swift cloudkit

我收到一个错误:“在尝试返回数据数组时使用未解析的标识符'数据'。我的代码如下所示。有人可以建议为什么会这样吗?

    public func loadData()->[Q] {
    let publicData = CKContainer.default().publicCloudDatabase
    let pred = NSPredicate(value: true)
    let query = CKQuery(recordType: "question", predicate: pred)
    publicData.perform(query, inZoneWith: nil, completionHandler: ({results, error in
        if(error != nil) {
            print(error?.localizedDescription)
        } else {
            if results!.count > 0 {
                var data = [Q]()
                for result in results!{
                    let quest = result.object(forKey: "question_name") as! String!
                    let a = result.object(forKey: "a") as! String!
                    let b = result.object(forKey: "b") as! String!
                    let c = result.object(forKey: "c") as! String!
                    let d = result.object(forKey: "d") as! String!
                    let answer = result.object(forKey: "answer") as! String!
                    let category = result.object(forKey: "category") as! String!
                    let final = Q(quest: quest!, A:a!, B: b!, C: c!, D: d!, answer: answer!, category: category!)
                    data.append(final)
                }
            }
        }
    }))
    return data
}

1 个答案:

答案 0 :(得分:1)

不!,不!,不!,永远不会使用sleep来解决异步任务!那是可怕的。

  • 为方便起见,请创建包含successfailure案例及相关类型的枚举

    enum Result {
      case success([Q]), failure(Error)
    }
    
  • loadData返回data或完成处理程序中的error。我删除了一堆冗余的括号,感叹号和数组的空检查。如果没有错误且没有匹配的数据,则返回Q的空数组。

    public func loadData(completion: @escaping (Result)->() ) {
      let publicData = CKContainer.default().publicCloudDatabase
      let pred = NSPredicate(value: true)
      let query = CKQuery(recordType: "question", predicate: pred)
      publicData.perform(query, inZoneWith: nil, completionHandler: {results, error in
        if error != nil {
         completion(.failure(error!))
        } else {
          var data = [Q]()
          for result in results! {
            let quest = result.object(forKey: "question_name") as! String
            let a = result.object(forKey: "a") as! String
            let b = result.object(forKey: "b") as! String
            let c = result.object(forKey: "c") as! String
            let d = result.object(forKey: "d") as! String
            let answer = result.object(forKey: "answer") as! String
            let category = result.object(forKey: "category") as! String
            let final = Q(quest: quest, A:a, B: b, C: c, D: d, answer: answer, category: category)
            data.append(final)
          }
          completion(.success(data))
        }
      })
    }
    
  • 调用函数

    loadData { result in
      switch result {
      case .success(let data): print(data) // do something with the result
      case .failure(let error): print(error)
      }
    }