Swift:是否可以使用循环创建匿名函数而不返回?

时间:2015-09-04 10:02:00

标签: swift closures

让我们看看工作示例:

let numbers: [Int] = {
    var num:[Int] = []
    for i in 0...3{
        num.append(i)
    }
    return num
}()

是否可以避免在变量中保存状态并直接返回生成的值?
就像在这个例子中一样(我希望在i中返回所有[]):

let numbers: [Int] = {
  for i in 0...3{
        i
    }
}()

这会在最后一行产生错误        Missing return in a closure expected to return '[Int]'

1 个答案:

答案 0 :(得分:2)

在这种特殊情况下,以下就足够了:

let numbers = Array(0...3)

对于一般情况,例如,而不是:

let numbers2: [String] = {
    var ret: [String] = []
    for i in 0...3 {
        ret.append(join("", Repeat(count: i, repeatedValue: "\(i)")))
    }
    return ret
}()
// -> ["", "1", "22", "333"]

您可以使用map

let numbers: [String] = map(0...3) { i in
    join("", Repeat(count: i, repeatedValue: "\(i)"))
}
// -> ["", "1", "22", "333"]