【问题标题】:Adapting an async method with closure to a syncronous method with return type将带闭包的异步方法适配为带返回类型的同步方法
【发布时间】:2017-03-02 17:56:02
【问题描述】:

我是 swift 新手,在任何主要线程工作方面都没有过多的经验,所以我正在尝试提高我的技能,希望得到一些帮助或指导。这是一个我似乎无法弄清楚的概念。

我有一个类通过输入和输出流进行通信,应用程序通过输出流发送,并从输入流中读取结果。现在我已经创建了通过回调发送异步的方法,但我希望能够同步发送,并在更高级别处理线程。 目前我的沟通方式是这样的:

typealias CommunicationCallback = ((CommunicationResult) -> Void)

func sendAsync(send message: String, closure: @escaping CommunicationCallback) {
    DispatchQueue.global().async { [weak self] in
            guard let strongSelf = self else {
                return
            }
            let messagePair = MessagePair(SendReceiveResult(sent: message, received: nil),
                                  closure)

            strongSelf.writeQueue.enqueue(messagePair)
            strongSelf.writeFromQueue() //Calls the CommunicationCallback closure after it has read result
        }

}

func sendSyncronized(send message: String) -> CommunicationResult {
    ???
}

有没有像上面那样包装异步的通用方法? 万一我认为这是完全错误的,在某些情况下我想简单地打电话

let result = sendSyncronized("foo")

而不是做

send("foo", closure: { result in
    switch result {
    case .a:
        foo()
    base .b:
        bar()
    }
})

每次,因为在某些情况下,我需要在等待上一个结果的同时进行许多顺序写入。 欢迎任何帮助!

【问题讨论】:

    标签: ios swift multithreading asynchronous closures


    【解决方案1】:

    也许您可以使用可选的返回类型。

    typealias CommunicationCallback = ((CommunicationResult) -> Type?)
    

    在异步方法中返回 nil,在同步方法中返回值。使用 if let 检查可选绑定是否成功。如果没有,无论如何你都需要从闭包中获取价值。

    【讨论】:

      猜你喜欢
      • 2019-06-04
      • 2013-03-26
      • 2019-04-05
      • 1970-01-01
      • 2020-08-27
      • 2019-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多