是否有方法直接检索Swift中闭包返回的值,键入闭包的返回类型,而不是:()->;类型

是否有方法直接检索Swift中闭包返回的值,键入闭包的返回类型,而不是:()->;类型,swift,closures,Swift,Closures,这是一个仅仅以优雅为目标的问题,但是有没有办法让下面的代码在Swift中工作?我知道代码不起作用,我想要的是闭包中代码的结果存储在常量中。潜在的理论问题是,是否可以使用Int类型而不是()类型->Int从闭包中检索返回值。 非常感谢您的帮助或评论 let tableWithBooleans: [Bool] = Array(repeating: false, count: 10) tableWithBooleans[0] = true tableWithBooleans[5] = true

这是一个仅仅以优雅为目标的问题,但是有没有办法让下面的代码在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

改为使用高阶函数

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}
(from)。或者更易于阅读,imo:
tableWithBooleans.lazy.map{$0?1:0}。reduce(0,+)