ios - 使用带有完成 block 的自定义运算符

标签 ios swift asynchronous swift2

简而言之,假设我定义了一个运算符:

infix operator <~ {
    associativity left
    precedence 160
}

假设我正在使用这个运算符在两个对象之间做一些工作,所以我定义了这样的函数:

func <~ <T: FirstProtocol, U:SecondProtocol>(lhs: T, rhs: U) {
    //async request
}

现在我们无法返回任何内容,因为运算符函数正在执行异步工作,我们也不能在闭包中使用更多参数。因为异步函数可能会运行几秒钟,所以我需要一个回调,该回调将在异步任务完成时运行。问题是是否可以将运算符与异步函数一起使用?我尝试了各种解决方案,但似乎都不起作用。

完美的解决方案如下所示:

something <~ somethingElse {
    error in
    //async call finished
}

最佳答案

不幸的是,something <~ somethingElse { err in ... }是不可能的,因为编译器将其解释为 something <~ (somethingElse({ err in ... })) .

至少,你必须(something <~ somethingElse) { err in ... } 。在 Playground 中尝试一下:

import Foundation

infix operator <~ {
associativity left
precedence 160
}

func <~(lhs: Int, rhs: Int) -> ((Int) -> Void) -> Void {
    return { callback in
        dispatch_async(dispatch_get_main_queue()) {
            callback(lhs + rhs)
        }
    }
}

let a = 1
let b = 2

(a <~ b) { result in
    println("OK: \(result)")
}

dispatch_main()

关于ios - 使用带有完成 block 的自定义运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32329682/

相关文章:

ios - 序列化我的自定义 nsobject 以通过 http 发送

ios - UILabel/UITextField 不使用异步 HTTP 请求更新

javascript - 错误 - HTML 中的异步 adsense 代码

.net - 如何等待 Azure 搜索完成索引文档?用于集成测试目的

javascript - 是否可以在 react-native 的构造函数中调用异步函数?

ios - 在 UICollectionView 上 float UIButton

ios - 将 Cocoapod 添加到 Cocoapod

ios - 如何从 JSON 解析图像

ios - Swift 4 UICollectionView 检测滚动结束

swift - 如何使用 Swift 从 ViewController 读取 AppDelegate 中的变量值