【发布时间】: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
【问题讨论】:
-
该代码不会崩溃,因为它甚至无法编译。
-
你是对的 :) 我编辑了这个问题。