4 ms·
A good example is a function like map() that applies a closure over the elements of a collection. In rust the compiler will prevent you from modifying the colle
by benmmurphy 7y ago
A good example is a function like map() that applies a closure over the elements of a collection. In rust the compiler will prevent you from modifying the collection from the closure. In swift the collection author has to make the implementation do something intelligent if the collection changes. This 'intelligent' thing usually means a slower implementation. For example in Rust map() for Vector can load the address of the buffer into a register and length into a register and assume they won't change. In the swift implementation it would have to reload the pointer to the buffer and the length every time the user code returned because the Array might have been modified.
- ridiculous_fish 7y agoSwift arrays are value types, how would you modify the array from inside map?
- benmmurphy 7y agovar x = [1, 2, 3]; let y = x.map( { v -> Int in print("got \(v)") x.removeAll() return 1 }) print("x: \(x)") print("y: \(y)") got 1 got 2 got 3 x: [] y: [1, 1, 1] I don't know much about swift but this shows the closure is able to mutate the Array. I guess value types are captured by reference by a closure.