xcode 在 Swift 中迭代一个集合:var 与 let

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33697364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 08:12:15  来源:igfitidea点击:

Iterating over a collection in Swift: var vs. let

xcodeswift2

提问by Dominik Palo

I have a method that iterates over an array and call other method with every element as argument. If I declare this method as:

我有一个方法可以遍历数组并以每个元素作为参数调用其他方法。如果我将此方法声明为:

func didFinishedListFiles(files: [FileModel]) {
    for var fileData in files {
        self.downloadSingleFile(NSUUID(UUIDString: fileData.uuid!)!);
    }
}

Xcode shows a warning:

Xcode 显示警告:

Variable 'fileData' was never mutated; consider changing to 'let' constant

变量“fileData”从未发生过变异;考虑更改为“让”常量

But if I change varto let:

但如果我var改为let

func didFinishedListFiles(files: [FileModel]) {
    for let fileData in files {
        self.downloadSingleFile(NSUUID(UUIDString: fileData.uuid!)!);
    }
}    

Xcode shows an error:

Xcode 显示错误:

'let' pattern cannot appear nested in an already immutable context

“let”模式不能嵌套在已经不可变的上下文中

How is a correct way to implement it without any warnings/errors?

如何在没有任何警告/错误的情况下正确实施它?

回答by rickster

The for-inpattern implicitly uses a constant binding (in the scope it creates. That is, your fileDatabinding is automatically a local let, and therefore constant for each pass through the loop.

for-in模式隐含采用恒定结合(在其创建的范围也就是说,你的。fileData结合自动在本地let,因此每个一次通过循环不断。

So the following:

所以如下:

for fileData in files { /*...*/ }

...is equivalent to :

...相当于:

var index = 0
while index < files.count {
    let fileData = files[index]
    //...
    index += 1
}

You'd want to add varto the for-inbinding only when you want to mutate that binding -- that is, if it's an object reference that you want to be able to point at something else during a single pass through the loop, or a value type that you want to be able to change. But it doesn't look like you're doing either of those things, so using varfor this binding would be superfluous here.

仅当您想改变该绑定时,您才想要添加varfor-in绑定 - 也就是说,如果它是一个对象引用,您希望能够在单次循环期间指向其他内容,或一个值您希望能够更改的类型。但看起来您并没有做这些事情中的任何一件,所以var在这里使用for this binding 是多余的。

(Swift 3 got rid of a lot of the places where you could make implicitly immutable bindings mutable, but left for varas an exception — it's still possible if you want to change something during a loop.)

(Swift 3 去掉了很多可以使隐式不可变绑定可变的地方,但for var作为一个例外留了下来——如果你想在循环中改变某些东西,它仍然是可能的。)