How can I change values inside array without a loop Swift

前端 未结 2 1605
感动是毒
感动是毒 2021-01-26 16:59

I have a bool array

For example:

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

and I want to change all the elements from inde

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-26 17:48

    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.

提交回复
热议问题