XmasRights
XmasRights

Reputation: 1509

Map or Copy in Swift

I recently wrote an extension to replace a single item in an immutable array, and found two good approaches:

Copy:

extension Array
{
    func replacingItem(at index: Int, with item: Element) -> Array
    {
        precondition(index < self.count)
        var copy = self
        copy[index] = item
        return copy
    }
}

Map:

extension Array
{
    func replacingItem(at index: Int, with item: Element) -> Array
    {
        precondition(index < self.count)
        return self.enumerated().map { $0.offset == index ? item : $0.element }
    }
}

Is one of these two approaches better than the other? What are the differences in how each method is run?

Upvotes: 1

Views: 239

Answers (1)

vadian
vadian

Reputation: 285069

Copy

makes a copy of the current array (self) in all and replaces the given element at given index (quasi o(1)).

Map

creates a new array and iterates over the current array (self). In each iteration it appends either the current element or the given element if the index matches the given index (quasi o(n)).


The difference is that Map is performing a repeat loop under the hood with a check for each item which is much more expensive than to copy the object instantly and update the desired item once, so Copy is the more efficient way.

Upvotes: 2

Related Questions