Teekachu_
Teekachu_

Reputation: 1

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

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

Upvotes: 0

Views: 165

Answers (1)

Martin R
Martin R

Reputation: 539805

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

Upvotes: 3

Related Questions