简体   繁体   中英

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:

Variable 'n' was never mutated; consider changing to 'let' constant.

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.

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 .

To fix that, change

var n = n + 1

To

n = n + 1

3 little notes:

a) If you read carefully messages from Xcode, you will understand about vars' lifetime and usage. ( "Variable 'n' was never mutated; consider changing to 'let' constant" )

b) you have two var with same name in different scope

c) the you enter "for", n on the left will be computed using N in outer scope, so inner n will always be == 2

d) using debugger You will see as in picture.

在此处输入图片说明

Those are two different variables named n . One is unchanged and one is created for each new iteration of the for loop.
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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