我收到“变异运算符的左侧不可变”..<“返回不可变值”错误
我阅读了另一篇关于改变值的文章,但我不知道这些解决方案如何应用。
代码(和注释):
//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
}
修改后的代码:
//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
}
谢谢!
我在这里也遇到同样的错误......
//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)
}
修改:
//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)
}
谢谢!
最佳答案
抛出错误的行是:
for intJ in 0 ..< 2 += 1{
+=
运算符是一个变异运算符,这意味着它告诉 Swift 获取其左侧的任何内容并更改它,在本例中是添加右侧的任何内容。
所以你在这里告诉 Swift 的是,取 0 ..< 2
并将其更改为 (0 ..< 2) + 1
。这会引发错误,因为 ..<
运算符返回一个不可变的范围 - 一旦创建,就无法更改。
即使您可以改变一个范围,这也可能不是您想要做的。从上下文来看,您可能想在右侧添加 1,在这种情况下,您只需删除 =
即可。 :
for intJ in 0 ..< 2 + 1{
这只是将右侧变为 3,因此循环变为 [0, 1, 2]。
或者也许您只是想告诉它每次都加 1,例如 i += 1
在标准 C 风格的 for 循环中。如果是这样的话,你就不需要这里了。按 1 索引是默认行为,因此您可以忽略整个 += 1
位:
for intJ in 0 ..< 2 {
或者,如果您需要增加 1 以外的值,则可以使用 Strideable protocol ,看起来像:
for intJ in stride(from: min, to: max, by: increment) {
只需替换 min
, max
和increment
用适当的数字。
关于swift3 - 更改为 Swift 3 后发生突变运算符错误,已研究问题,但无法解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40388873/