Duck
Duck

Reputation: 35933

Converting a mutating array to non-mutating in place

I have a code like this:

let array = self.doSomething(Array<UInt8>([10, 29, 33]).reverse())

the problem is that doSomething is expecting a non-mutating array and the reverse() function returns a mutating one.

How do I convert Array<UInt8>([10, 29, 33]).reverse() to a non-mutating array in place, without creating another line of code, something like

let array = self.doSomething(Array<UInt8>([10, 29, 33]).reverse().nonMutating)

Upvotes: 0

Views: 143

Answers (1)

Rob Napier
Rob Napier

Reputation: 299275

There are no "mutating" and "non-mutating" Arrays. The issue is that you're likely creating a ReversedCollection, and you want an Array. You can create that by creating an Array from the collection:

let array = self.doSomething(Array(Array<UInt8>([10, 29, 33]).reversed()))

Note that the method is reversed() here not reverse(). reverse() returns Void (which you may be mistaking for a "mutating array").

If you mean "I want to mutate an array in place and then pass it to something else," that is two actions, and it takes two statements. While it's possible to work around with extra functions, there's little point to that. reversed() is O(1) and Array.init(collection) is O(N), so the whole thing is O(N), which is the same as Array.reversed. If there is a memory allocation concern, then add the extra line. It is very tricky to pass arrays to mutating functions and be absolutely certain no copies will be made (Swift doesn't provide any promises around copy avoidance).

Typically I would rewrite doSomething here to accept a Collection rather than an Array.

Upvotes: 2

Related Questions