# In-place map for MutableCollection

**URL:** <https://forums.swift.org/t/in-place-map-for-mutablecollection/11111>\
**Category:** Pitches\
**Created:** [March 18, 2018, 12:29pm UTC](https://forums.swift.org/t/in-place-map-for-mutablecollection/11111 "2018-03-18T12:29:17Z")\
**Posts on this page:** 1\
**Showing post:** 14

<div class="post-metadata">

**Author:** ![Nevin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nevin/32/617_2.png) [@Nevin](https://forums.swift.org/u/Nevin)\
**Post date:** [March 18, 2018, 6:24pm UTC](https://forums.swift.org/t/in-place-map-for-mutablecollection/11111/14 "2018-03-18T18:24:05Z")

</div>

> [@Chris\_Eidhof](#):
>
> ```swift
> extension MutableCollection {
> mutating func mapInPlace(_ x: (inout Element) -> ()) {
> for i in indices {
> x(&self[i])
> }
> }
> }
> 
> ```

This implementation falls into a performance trap, as described in the [documentation for `indices`](https://developer.apple.com/documentation/swift/collection/1641719-indices#discussion). Essentially, `indices` might hold a reference to `self`, in which case mutating `self` while iterating over `indices` creates an extra copy of `self`. In the standard library, this occurs for `Dictionary.Values`.

The recommended approach is to manually advance an index.

```swift
extension MutableCollection {
    mutating func mutateAll(_ f: (inout Element) throws -> ()) rethrows {
        var i = startIndex
        while i != endIndex {
            try f(&self[i])
            formIndex(after: &i)
        }
    }
}

```

Also, if you want to directly pass in a function (eg. `sin`) rather than a closure, then the parameter should not be `inout`:

```swift
extension MutableCollection {
    mutating func mutateAll(_ f: (Element) throws -> Element) rethrows {
        var i = startIndex
        while i != endIndex {
            self[i] = try f(self[i])
            formIndex(after: &i)
        }
    }
}

```

The difference is in how you call it:

```swift
x.mutateAll{ $0 *= $0 } // inout
x.mutateAll{ $0 * $0 } // non-inout
x.mutateAll(sin) // non-inout

```

---

_[View the full topic](https://forums.swift.org/t/in-place-map-for-mutablecollection/11111)._
