Search code examples
swiftconstantslet

Let type in a for in loop


I'm playing around with Swift. Why is it possible to declare let type in a for loop? As far as I know, let means constant, so I'm confused.

    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

    }

Solution

  • The lifespan of the inPct constant is only during the loop iteration since it is block scoped:

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

    In every iteration inPct refers to a new variable. You can not assign to any of the inPcts in any iteration since they were declared with let:

    for i in 1...5 {
        let x = 5
        x = 6 // compile error
    }