0

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?"].

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

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) }

1 Answer 1

3

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?"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.