【问题标题】:How can I replace a string in an array with a new string?如何用新字符串替换数组中的字符串?
【发布时间】:2015-09-27 15:13:38
【问题描述】:

我正在使用 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.

}

错误表示数组超出索引。

【问题讨论】:

  • 哪一行出现错误?另外,您的行中创建 newValue 的内容是什么?此外,您最好为此使用地图功能。
  • 您可以将myStrings[i] 替换为另一个值,但如果索引不存在,则无法在那里创建值。这就是为什么您使索引超出范围的原因。尝试使用append 将项目添加到数组中。

标签: arrays string swift swift2


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-03-21
    • 2015-12-25
    • 2022-10-15
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 2013-11-08
    相关资源
    最近更新 更多