whok mok
whok mok

Reputation: 47

How to change $0 to be mutable?

I would like to replace specific element in array with another element like this:

let replace = ["123","87","123","765","som","123","op","123"].map {$0 == "123" ? $0 = "replace" : $0}

but I cannot do this because compiler throws me error:

error: cannot assign to value: '$0' is immutable

So, Is this possible to change $0 to be mutable?

Upvotes: 2

Views: 3281

Answers (2)

EmilioPelaez
EmilioPelaez

Reputation: 19912

You don't need $0 to be mutable. map will use whatever value you return, so you can use the last map like this:

.map { $0 == "123" ? "replace" : $0 }

When that map closure is run, whenever $0 matches "123", it will return replace, otherwise it will return the current value.

Upvotes: 8

Misternewb
Misternewb

Reputation: 1096

This closure parameter in map function is immutable and can not be changed, as it is passed by value and gets copied from original value. Changing parameter's value is possible, if it is marked by inout, which is not your case here.

Upvotes: -1

Related Questions