Jim*_*ire 5 mutable operator-keyword swift3 xcode8
我收到“变异运算符的左侧不可变”..<“返回不可变值”错误
我阅读了关于变异值的另一篇文章,但我无法弄清楚这些解决方案是如何应用的。
代码(和评论):
//populate array of 3 random numbers using correct answer and 2 incorrect choices
func insertIntoArray3(_ randomNumber: Int) -> Int {
for intJ in 0 ..< 2 += 1{
if arrayIndex != 3 {
checkIfExists(randomNumber)
if ifExists {
let randomNumber = 1 + random() % 10
insertIntoArray3(randomNumber)
} else {
array3[arrayIndex] = (randomNumber)
arrayIndex = arrayIndex + 1
}
}
}
return randomNumber
}
Run Code Online (Sandbox Code Playgroud)
修订代码:
//populate array of 3 random numbers using correct answer and 2 incorrect choices
func insertIntoArray3(_ randomNumber: Int) -> Int {
for _ in 0 ..< 2 + 1{
if arrayIndex != 3 {
checkIfExists(randomNumber)
if ifExists {
let randomNumber = 1 + arc4random() % 10
insertIntoArray3(Int(randomNumber))
} else {
array3[arrayIndex] = (randomNumber)
arrayIndex = arrayIndex + 1
}
}
}
return randomNumber
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
我也在这里遇到同样的错误......
//this function populates an array of the 40 image names
func populateAllImagesArray() {
for intIA in 1 ..< 11 += 1 {
tempImageName = ("\(intIA)")
imageArray.append(tempImageName)
tempImageName = ("\(intIA)a")
imageArray.append(tempImageName)
tempImageName = ("\(intIA)b")
imageArray.append(tempImageName)
tempImageName = ("\(intIA)c")
imageArray.append(tempImageName)
}
//println("imageArray: \(imageArray) ")
//println(imageArray.count)
}
Run Code Online (Sandbox Code Playgroud)
修改:
//this function populates an array of the 40 image names
func populateAllImagesArray() {
for intIA in 1 ..< 11 + 1 {
tempImageName = ("\(intIA)")
imageArray.append(tempImageName)
tempImageName = ("\(intIA)a")
imageArray.append(tempImageName)
tempImageName = ("\(intIA)b")
imageArray.append(tempImageName)
tempImageName = ("\(intIA)c")
imageArray.append(tempImageName)
}
//println("imageArray: \(imageArray) ")
//println(imageArray.count)
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
引发错误的行是:
for intJ in 0 ..< 2 += 1{
Run Code Online (Sandbox Code Playgroud)
该+=运算符是一个变异运算符,这意味着它告诉 Swift 获取其左侧的任何内容并更改它,在本例中是添加右侧的任何内容。
所以你在这里告诉 Swift 的是,将0 ..< 2其更改为(0 ..< 2) + 1. 这会引发错误,因为该运算符返回一个不可变的..<范围- 一旦创建,就无法更改。
即使您可以改变一个范围,这也可能不是您想要做的。从上下文来看,您可能想在右侧添加 1,在这种情况下,您只需删除=:
for intJ in 0 ..< 2 + 1{
Run Code Online (Sandbox Code Playgroud)
这只是将右侧变为 3,因此循环进入 [0, 1, 2]。
或者您可能只是想告诉它每次都加 1,就像i += 1标准 C 风格的 for 循环一样。如果是这样的话,你就不需要这里了。按 1 索引是默认行为,因此您可以省略整个+= 1位:
for intJ in 0 ..< 2 {
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要增加 1 以外的值,则可以使用Strideable 协议,如下所示:
for intJ in stride(from: min, to: max, by: increment) {
Run Code Online (Sandbox Code Playgroud)
只需将min,max和替换increment为适当的数字即可。
| 归档时间: |
|
| 查看次数: |
6036 次 |
| 最近记录: |