Search code examples
swiftimmutabilitymutability

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?


Solution

  • 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.