简体   繁体   English

快速循环中的 let 或 var

[英]Let or var in swift loop

Here is a sample of Swift UI code, a simple loop with a "variable" number value being changed.这是一个 Swift UI 代码示例,一个简单的循环,其中“变量”数值被更改。

    import SwiftUI

struct ContentView: View {
    let a = 1.0
    let a = 2.0 // invalid redeclaration

    var body: some View {
        VStack {
            ForEach (0..<3) {i in
                var number = i+1 // variable number was never mutated - use let instead
                Text("var \(number)")
                }
            ForEach (0..<3) {i in
                let number = i+1
                Text("let \(number)")
                }
//            ForEach (0..<3) {i in
                //number = i+1 // cannot find number in scope
//                Text("nothing \(number)")
//                }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

The bizarre thing is that :奇怪的是:

  • "var number" : a recommandation to use "let" because "there are no change in the value of number" “var number”:建议使用“let”,因为“number 的值没有变化”
  • "let number" : is OK despite it is in a loop and therefore modified several times "let number" :尽管它处于循环中并因此修改了多次,但还是可以的

Both work but I am surprised that let (designed for constants) is used and even preferred within a loop.两者都有效,但令我惊讶的是,在循环中使用甚至首选 let(为常量设计)。 Any explanation ?有什么解释吗?

Paradoxes rely on some misunderstanding and therefore make progressing.悖论依赖于一些误解,因此会取得进展。

Here, the question is : what is the scope with the for(ForEach).在这里,问题是:for(ForEach) 的范围是什么。 In most languages, it is all the instructions between the for and its end.在大多数语言中,它是 for 和它的结尾之间的所有指令。 Here, the scope is each instance of the iteration .在这里,范围是迭代的每个实例 Then a let, reserved for constants, is fully adequate since the variable is never modified within each instance of the iteration.然后,为常量保留的 let 就足够了,因为在迭代的每个实例中都不会修改变量。

If one wants to cumulate the variable, say number, number must be declared in the environment of the for loop.如果要累积变量,比如说数字,数字必须在 for 循环的环境中声明。

Thanks to all who commented.感谢所有评论的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM