Kevin
Kevin

Reputation: 1223

How can I change values inside array without a loop Swift

I have a bool array

For example:

 var myBool: [Bool] = [true, true, false, true ,false]

and I want to change all the elements from index 1 to index 3

something like this:

 myBool[1...3] = true // [true, true, true, true, false]

I don't want to use for loop because I have a very big array which is changing fast and the loop is too slow to handle this kind of change.

Upvotes: 0

Views: 712

Answers (2)

vadian
vadian

Reputation: 285069

Any mutable collection responds to replaceSubrange:with:

var myBool = [true, true, false, true, false]
myBool.replaceSubrange(1...3, with: Array(repeating: true, count: 3))

or (credits to MartinR)

var myBool = [true, true, false, true, false]
let range = 1...3
myBool.replaceSubrange(range, with: repeatElement(true, count: range.count))

Upvotes: 3

David Pasztor
David Pasztor

Reputation: 54706

There's no way to achieve this without iterating through all indices of the array that you want to change, so the minimum complexity of your change will be the same regardless of how you achieve this - even if you don't directly use a loop, the underlying implementation will have to use one.

You can assign values directly to a range of indices in your array, but you need to assign another ArraySlice, not a single Element.

var myBool: [Bool] = [true, true, false, true ,false]
let range = 1...3
myBool[range] = ArraySlice(range.map { _ in true })

Bear in mind that the complexity of this will be the same as a for loop. If you are experiencing slowness, that's most probably not because of the for loop.

Upvotes: 2

Related Questions