简体   繁体   English

循环遍历数组中所有元素中的字符

[英]Looping over the characters within all elements in an array

Code newbie here stuck on a seemingly easy problem.代码新手在这里遇到了一个看似简单的问题。

Say I want to add an ?说我想添加一个 ? to the beginning and ending of all elements in an array.到数组中所有元素的开头和结尾。 so if my array is ["abc","def"] , my output would be ["?abc?"," ?def?"].所以如果我的数组是 ["abc","def"] ,我的输出将是 ["?abc?"," ?def?"]。

I tried to use for loop / for each but the error message is saying : Cannot use mutating member on immutable value: 'word' is a 'let' constant我尝试使用 for 循环 / for each 但错误消息说:无法在不可变值上使用变异成员:'word' 是一个 'let' 常量

This is what I had so far and did not workout:这是我到目前为止没有锻炼的:

var array = ["abc","def"]

array.forEach { (word) in
 word.insert("?", at: word.startIndex)
 word.insert("?", at: word.endIndex) }

The error message is for example explained in "Cannot assign to" error iterating through array of struct : The loop variable is a (constant) copy of the current array element (a string) and cannot be mutated.例如,错误消息在迭代结构数组的“无法分配给”错误中进行了解释:循环变量是当前数组元素(字符串)的(常量)副本,不能改变。

A possible solution is to map each array element to the new word.一种可能的解决方案是将每个数组元素映射到新单词。 That creates a new array which can then be assigned to the original one:这将创建一个新数组,然后可以将其分配给原始数组:

var array = ["abc", "def"]
array = array.map { "?" + $0 + "?" }
print(array) // ["?abc?", "?def?"]

Alternatively iterate over the array indices so that you can modify the actual array elements:或者迭代数组索引,以便您可以修改实际的数组元素:

var array = ["abc", "def"]
for i in array.indices {
    array[i].insert("?", at: array[i].startIndex)
    array[i].insert("?", at: array[i].endIndex)

    // Or:
    // array[i] = "?" + array[i] + "?"
}
print(array) // ["?abc?", "?def?"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM