让我们输入for循环

Tos*_*shi 4 constants let swift

我正在玩Swift.为什么可以let在for循环中声明类型?据我所知,let意味着不变,所以我很困惑.

    func returnPossibleTips() -> [Int : Double] {
        let possibleTipsInferred = [0.15, 0.18, 0.20]
        //let possibleTipsExplicit:[Double] = [0.15, 0.18, 0.20]

        var retval = Dictionary<Int, Double>()
        for possibleTip in possibleTipsInferred {
            let inPct = Int(possibleTip * 100)
            retval[inPct] = calcTipWithTipPct(possibleTip)
        }

    return retval

    }
Run Code Online (Sandbox Code Playgroud)

Ben*_*aum 5

inPct常量的生命周期仅在循环迭代期间,因为它是块作用域:

for i in 1...5 {
    let x = 5
}
println(x) // compile error - Use of unresolved identifier x
Run Code Online (Sandbox Code Playgroud)

在每次迭代中都inPct引用一个新变量.您无法inPct在任何迭代中分配任何s,因为它们是使用let以下方式声明的:

for i in 1...5 {
    let x = 5
    x = 6 // compile error
}
Run Code Online (Sandbox Code Playgroud)