【问题标题】:Convert a non-escaping closure to an escaping one or the other way将非转义闭包转换为转义一种或另一种方式
【发布时间】:2018-10-05 14:57:56
【问题描述】:

我正在创建一个模板模式,以便在我的单元测试中轻松地在 Nimble 和 XCTAssert 之间切换。

所以我有一个协议

protocol Assertable {
  func notNil(_ expression: @autoclosure () throws -> Any?, file: StaticString, line: UInt)
}

not nil 的 XCTAssert 实现是这样的:

func XCTAssertNotNil(_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String = default, file: StaticString = #file, line: UInt = #line)

而 Nimber 的则是:

func expect<T>(_ expression: @autoclosure @escaping () throws -> T?, file: FileString = #file, line: UInt = #line) -> Expectation<T>

基本上唯一的区别是一个在逃跑而不是另一个。

我的问题是,如果我用@escaping 声明我的模板,XCTAssertNotNil(expression) 将不再起作用,因为转义的闭包永远不能被视为nil,因此 XCTAssertNotNil 将始终为 true 而 XCTAssertNil 将始终为 false。

如果我不关心我的模板非转义,那么 Nimble 将不会高兴,因为它需要转义闭包。

怎么办?

【问题讨论】:

    标签: swift closures


    【解决方案1】:

    将非转义转换为转义闭包的唯一方法是执行块。

    func XCTAssertNotNil(_ expression: @autoclosure () throws -> Any?) {
        do {
            let performed = try expression()
    
            expect(performed)
        } catch {
            expect({ throw error })
        }
    }
    

    反之亦然不成问题:

    func expect<T>(_ expression: @autoclosure @escaping () throws -> T?) {
        XCTAssertNotNil(expression)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-26
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多