【问题标题】:Swift2 closure that throws抛出的 Swift2 闭包
【发布时间】:2015-10-27 06:31:59
【问题描述】:

我正在尝试创建一个可以抛出的闭包,并将其作为参数传递给另一个函数。例如:

extension NSManagedObjectContext {

  /// The same as performBlockAndWait, except it can handle closures that throw.
  func performBlockAndWaitOrThrow(block: (() -> throws Void)) throws {
    // ...
    try block()
  }
}

注意 |block|参数是一个可以抛出的闭包。

但是,这不会编译。有没有办法做到这一点?

【问题讨论】:

    标签: ios macos swift swift2


    【解决方案1】:

    throws 关键字应该出现在箭头之前。这样编译:

    extension NSManagedObjectContext {
    
        /// The same as performBlockAndWait, except it can handle closures that throw.
        func performBlockAndWaitOrThrow(block: (() throws -> Void)) throws {
            // ...
            try block()
        }
    }
    

    【讨论】:

    • Derp,我已经盯着这段代码太久了。谢谢!
    • 这实际上并没有做任何事情,只是运行一个抛出的闭包......?
    • 问题是关于传递抛出闭包的语法,所以这就是所有答案。
    猜你喜欢
    • 2016-01-07
    • 1970-01-01
    • 2020-10-09
    • 2017-09-04
    • 2023-04-02
    • 2019-08-30
    • 2020-09-26
    • 2011-02-09
    • 2018-06-10
    相关资源
    最近更新 更多