3

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?

2
  • 1
    Don't use inout. If you must then you will need to iterate over the array, building a new array with the modified words or use an index variable rather than enumeration Commented Dec 1, 2016 at 21:31
  • Closely related: Changing The value of struct in an array Commented Dec 1, 2016 at 21:33

1 Answer 1

1

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])
}
Sign up to request clarification or add additional context in comments.

2 Comments

Deleting my answer after seeing your's. I never knew this and posted a less "Swifty" version of your answer! Nice!
Note that words still needs to be declared with var, not let.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.