【问题标题】:How to wait for asynchronous part in function in swift?如何在swift中等待函数中的异步部分?
【发布时间】:2021-08-10 21:20:21
【问题描述】:

我有一个必须返回计算值的函数,问题是返回的值是在函数开头初始化的值。函数的一部分是异步的,所以这部分在函数返回值之前没有时间执行。

我不知道如何等待代码的异步部分。

所以代码的异步部分中的打印返回正确的值,但是在返回之前的打印,返回一个使用变量placeMarkCoordinates变量的初始化值计算的值,该变量还没有来得及修改。

func getDistance(placeMarkLocation: MKLocalSearchCompletion, currentLocation: CLLocation) -> String {
  let searchRequest = MKLocalSearch.Request(completion: placeMarkLocation)
  let search = MKLocalSearch(request: searchRequest)
  var placeMarkCoordinates: CLLocation = CLLocation(latitude: 0, longitude: 0)
    
  // Asynchronous part:
  search.start { (response, error) in
    guard let coordinate = response?.mapItems[0].placemark.coordinate else {
      return
    }

    placeMarkCoordinates = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
    print(currentLocation.distance(from: placeMarkCoordinates))
  }
    
  print(currentLocation.distance(from: placeMarkCoordinates))
  return "\(currentLocation.distance(from: placeMarkCoordinates).getDistanceString)"
}

【问题讨论】:

标签: swift asynchronous


【解决方案1】:

您不应该使用返回方法。相反,请在 getDistance 方法中使用闭包。

像这样声明方法:

func getDistance(placeMarkLocation: MKLocalSearchCompletion, currentLocation: CLLocation, completion: @escaping (String) -> ()) {
    // Within your async block, do:
    completion(yourReturnStringValue)

    // This way, no value leaves the method before the async process is finished
}

调用方法如下:

getDistance(placeMarkLocationValue, currentLocationValue) { returnStringValue in
    // Your returnStringValue can be used here
}

【讨论】:

  • 另外请注意,完成应该是在异步块中调用的最后一个代码,在它之前放置打印语句。
  • 谢谢,我想知道如何在 swiftui 上下文中,在 Text() 中使用它?
  • 抱歉,无法帮助您。不过应该不会太难
  • 您的问题标签是 Swift,而不是 SwiftUI。如果我的回答对您的情况不正确,也许您应该澄清您的问题。
  • @Guillaume,你有没有让它工作?
猜你喜欢
  • 1970-01-01
  • 2021-08-28
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 2023-01-27
  • 2018-07-20
  • 1970-01-01
相关资源
最近更新 更多