I have an array inside my EnvironmentObject that drives a few of my views. Now I need an update function for that array. Some elements might change, some may not.
Should I first check each element whether it "needs" the update and only write to the array if it does or am I overthinking it because Swift / SwiftUI will optimize out write operations that won't actually change data?
Here is an example:
func newValue(forIndex index: Int) -> Double {
if index % 5 == 0 {
return Double(index) + 0.5
}else {
return Double(index)
}
}
var array = Array(stride(from: 0.0, to: 1_000_000.0, by: 1))
for i in 0..<array.count {
let new = newValue(forIndex: i)
if new != array[i] {
array[i] = new
}
}
Or this...
for i in 0..<array.count {
array[i] = newValue(forIndex: i)
}
Clarification added: I am trying to avoid unnecessary data writes and UIupdates. I mean if one array element already is at 2.0 I don’t want to “change” it to 2.0 by setting it to 2.0 again and I certainly don’t want to cause a redraw in this case. Do I have to do this avoidance check myself or is Swift already doing it for me by optimization?