从私有 CloudKit 数据库中获取的数据未从函数返回

Fetched data from private CloudKit database not returning from function

我正在尝试从私有 ClouKit 数据库中获取一些数据。查询和谓词工作正常,因为我可以在 print(data) // 1 处看到数组中充满了所有数据。但是一旦它离开 perform(){} 数组就会重置为它在顶部定义的值并且它只是 returns 它们。

func fetchUserRecord() -> [Double] {
    var data: [Double] = [0, 1, 2]                              //demo data
    let aWeekAgo = Date().addingTimeInterval(-604800)
    
    let privateDB = CKContainer.default().privateCloudDatabase
    let predicate = NSPredicate(format: "Date > %@", aWeekAgo as NSDate)
    let query = CKQuery(recordType: "ProgressionValue", predicate: predicate)

    privateDB.perform(query, inZoneWith: nil) { records, error in
        guard let records = records else { return }
        for record in records {
            data.append(record["Value"] as! Double)
        }
        data.append(0.0)
        print(data)         // 1
    }
    print(data)             // 2
    return data
}

输出如下:

打印(数据)//1: [0.0, 1.0, 2.0, {大量双打}, 0.0]

打印(数据)//2: [0.0, 1.0, 2.0]

我错过了什么?

试用新的同步工具;

 func fetchUserRecord() async throws -> [Double]
 {
     var data: [Double] = [0, 1, 2]    // you don't really want the              
     let aWeekAgo = Date().addingTimeInterval(-604800)

    let privateDB = CKContainer.default().privateCloudDatabase
    let predicate = NSPredicate(format: "Date > %@", aWeekAgo as NSDate)
    let query = CKQuery(recordType: "ProgressionValue", predicate: predicate)
    let (values, cursor) = try await privateDB.records(matching: query, resultsLimit: 100)

    for r in values
    {
        if let rec = try? r.1.get()
        {                
            data.append(rec["value"] as Double)
        }
    }
    
    return x
        
  }

这样称呼它;

Task 
{
   do {
         data = try await fetchUserRecord()           
      }
      catch
      {
         print(error)
      }
 }