Bretsko Bretsko - 3 days ago 6
iOS Question

How to call a function with an `inout` argument on each element of array?

I have a function which takes

inout
argument

func modify(word: inout Word)


I need to call it on each element of array. Here is what I do

for word in words {
modify(word: &word)
}


but I get error
cannot pass immutable value as inout argument: 'word' is a 'let' constant


I tried to iterate through
map
words.map{ modify(word:&$0) }
, still the same error
cannot pass immutable value as inout argument: '0$' is immutable


Is there any way to call a function with an
inout
argument on each element of array?

Answer

When using the for word in words syntax, word is actually an immutable copy of the element in the array.

To modify the array directly, iterate over the indices instead:

for i in words.indices {
    modify(word: &words[i])
}

which is equivalent to (for arrays at least)

for i in 0..<words.count {
    modify(word: &words[i])
}
Comments