简体   繁体   English

Swift Programming Beginner:为什么在实现变量时我的循环中有错误?

[英]Swift Programming Beginner : Why is there an error in my loop when implementing a Variable?

When I try and run my code in Xcode playground I get a warning: 当我尝试在Xcode游乐场中运行代码时,收到警告:

Variable 'n' was never mutated; 变量“ n”从未被突变; consider changing to 'let' constant. 考虑更改为“ let”常量。

First of all, I am changing the variable in the body of the loop so why is it telling me to change it to a let (constant) data type. 首先,我正在循环的主体中更改变量,为什么它告诉我将其更改为let(恒定)数据类型。

func multiples (n : Int) {
  var n = 1

  for _ in (3 ..< 1000) {

    var n = n + 1

    let multiple3 = 3 * n

    print(multiple3)
  }
}

I am changing the variable in the body of the loop 我在循环体内更改变量

No, you're not. 不你不是。 The one in the body of the loop is a different n . 循环主体中的一个是另一个n

To fix that, change 要解决此问题,请更改

var n = n + 1

To

n = n + 1

3 little notes: 3个小注意事项:

a) If you read carefully messages from Xcode, you will understand about vars' lifetime and usage. a)如果您仔细阅读了Xcode的消息,您将了解vars的寿命和用法。 ( "Variable 'n' was never mutated; consider changing to 'let' constant" ) “变量'n'从未被突变;请考虑将其更改为'let'常量”

b) you have two var with same name in different scope b)您在不同范围内有两个具有相同名称的var

c) the you enter "for", n on the left will be computed using N in outer scope, so inner n will always be == 2 c)您输入“ for”时,将在外部范围中使用N计算左侧的n,因此内部n始终为== 2

d) using debugger You will see as in picture. d)使用调试器您将看到如图所示。

在此处输入图片说明

Those are two different variables named n . 这是两个名为n不同变量。 One is unchanged and one is created for each new iteration of the for loop. 一个不变,并且为for循环的每个新迭代创建一个。
The reason you can have two variables with the same name is that they exist in different scopes and the one inside the for loop temporarily overrides the one outside the loop for the duration of the loop but only inside it. 之所以可以使用两个具有相同名称的变量,是因为它们存在于不同的作用域中,并且for循环内的一个变量会在循环持续时间内暂时覆盖循环外的变量,但仅覆盖循环内的变量。

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

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