How to make async / await in Swift?

后端 未结 5 2024
别跟我提以往
别跟我提以往 2020-12-28 14:53

I would like to simulate async and await request from Javascript to Swift 4. I searched a lot on how to do it, and I thought I found the answer with DispatchQueue

5条回答
  •  我在风中等你
    2020-12-28 15:42

    In iOS 13 and up, you can now do this using Combine. Future is analogous to async and the flatMap operator on publishers (Future is a publisher) is like await. Here's an example, loosely based on your code:

    Future { promise in
      directions.calculate(options) { (waypoints, routes, error) in
         if let error = error {
           promise(.failure(error))
         }
    
         promise(.success(routes))
      }
     }
     .flatMap { routes in 
       // extract feature from routes here...
       feature
     }
     .receiveOn(DispatchQueue.main) // UI updates should run on the main queue
     .sink(receiveCompletion: { completion in
        // completion is either a .failure or it's a .success holding
        // the extracted feature; if the process above was successful, 
        // you can now add feature to the map
     }, receiveValue: { _ in })
     .store(in: &self.cancellables)
    

    Edit: I went into more detail in this blog post.

提交回复
热议问题