【问题标题】:Is there a way to retrieve directly the value returned from a closure in Swift, with type the return type of the closure and not: () -> Type有没有办法直接检索从 Swift 中的闭包返回的值,类型是闭包的返回类型而不是: () -> Type
【发布时间】:2021-01-06 18:01:09
【问题描述】:

这是一个仅针对优雅的问题,但是有没有办法使以下代码在 Swift 中工作?我知道代码不起作用,我想要的是闭包内代码的结果存储在一个常量中。潜在的理论问题是是否可以从闭包中检索返回值,类型为 Int 而不是类型 () -> Int。 非常感谢您的帮助或评论!

let tableWithBooleans: [Bool] = Array(repeating: false, count: 10)

tableWithBooleans[0] = true

tableWithBooleans[5] = true

let numberOfTrue: Int = {
            
    var result: Int = 0
            
    for i in 0...9 {
                
        if tableWithBooleans[i] {
                        
            result += 1
                        
        }
                                
    }

    return result

}

// I want the code to compile and numberOfTrue to be a constant equal to 2

【问题讨论】:

  • 该代码不会崩溃,因为它甚至无法编译。
  • 你是对的 :) 我编辑了这个问题。

标签: swift closures


【解决方案1】:

改用高阶函数

let numberOfTrue = tableWithBooleans.reduce(0) { $1 ? $0 + 1 : $0 }

现在,如果您仍想使用闭包代码,则应在结束 } 后添加 (),因为您将 {} 内的代码作为函数调用

let numberOfTrue: Int = {
    var result: Int = 0

    for i in 0...9 {
        if tableWithBooleans[i] {
            result += 1
        }
    }
    return result
}()

【讨论】:

  • 非常感谢,第二个解决方案正是我正在寻找的(用于更复杂的代码),第一个解决方案也是非常有用的,需要牢记。
  • 更高效(无中间数组)将是tableWithBooleans.reduce(0) { $1 ? $0 + 1 : $0 }(来自stackoverflow.com/a/39985033/1187415)。
  • 或更易读,imo:tableWithBooleans.lazy.map { $0 ? 1 : 0 }.reduce(0, +)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-23
  • 2013-07-02
  • 2015-08-18
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多