2015-09-27 155 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內封閉,以便能夠在封閉內使用它。