2015-09-27 176 views
0

我正在使用for循环来检查字符串数组。对于每个字符串,我都在为它找到一个新的值。找到新值后,我需要替换相应索引处的字符串。如何用新字符串替换数组中的字符串?

var myStrings = [String]() 

for var i = 0; i < myStrings.count; i++ { 

    let newValue: String = //Do some work to find the new value 

    myStrings[i] = newValue //This is what I thought would work, but I'm getting a crash and error saying that the array is out of index. 

} 

错误指出数组超出索引。

+1

哪条线给出错误?另外,你的行中有什么创建newValue?此外,你可能会更好地使用地图功能。 – Fogmeister

+1

您可以用另一个值替换'myStrings [i]',但如果索引不存在,则无法在其中创建值。这就是为什么你要索引超出范围。尝试使用'append'将项目添加到数组中。 – vacawama

回答

0

想通了。我寻找newValue的工作涉及到使用一些闭包。我必须重新定义i作为index内封闭,以便能够在封闭内使用它。

相关问题