我得到一个“变异运算符的左侧不可变”..<“返回不可变值”错误 我阅读了关于变异值的其他帖子,但我无法弄清楚这些解决方案是如何应用的. 代码(和评论):
//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.这会引发错误,因为...< operator返回一个不可变的范围 - 一旦创建,就无法更改. 即使你可以改变一个范围,这可能不是你想要做的.从上下文看起来可能你想在右侧添加1,在这种情况下你只需要摆脱=:
for intJ in 0 ..< 2 + 1{
这只是将右侧变为3,所以循环变为[0,1,2].
或者你可能只想告诉它每次增加1,就像标准C风格for循环中的i = 1一样.如果是这样的话,你不需要它.索引为1是默认行为,因此您可以省略整个= 1位:
for intJ in 0 ..< 2 {
或者如果你需要增加1以外的值,你可以使用Strideable protocol,它看起来像:
for intJ in stride(from: min,to: max,by: increment) {
只需用适当的数字替换min,max和increment即可.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。