0

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.

2 Answers 2

3

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))
Sign up to request clarification or add additional context in comments.

5 Comments

Or replaceSubrange(1...3, with: repeatElement(true, count: 3))
@MartinR Thanks, this is still better.
With respect to the question (“the loop is too slow”) it would be interesting to know if this is more efficient.
Hey, Can I achieve the same thing with a 2D array? I need to change the rows for example but I dont know how to access only the row to apply the function myBool = [ [true, true, false ,true], [false, false, true, true] ] myBool.replace.... [row]
I think so, instead of a single Bool the array element is a (sub)array.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.