加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 让我们输入for循环

发布时间:2020-12-14 04:39:22 所属栏目:百科 来源:网络整理
导读:我正在玩 Swift. 为什么可以在for循环中声明let类型?据我所知,让意思是不变的,所以我很困惑. func returnPossibleTips() - [Int : Double] { let possibleTipsInferred = [0.15,0.18,0.20] //let possibleTipsExplicit:[Double] = [0.15,0.20] var retval =
我正在玩 Swift.
为什么可以在for循环中声明let类型?据我所知,让意思是不变的,所以我很困惑.

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

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

    return retval

    }

解决方法

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

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

在每次迭代中,inPct指的是一个新变量.您不能在任何迭代中分配任何inPcts,因为它们是使用let声明的:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读