user509981
user509981

Reputation:

Memory safety in swift (inout param/long term access)

I was reading the memory safety chapter in swift, and wanted to try this exemple :

var stepSize = 1

func increment(_ number: inout Int) {
    number += stepSize
}

increment(&stepSize)

Event if it says that there is an error because of the conflicting access to the stepsize variable (long term access in writing), it actually compiles and give me the right answer (ie 2).

Can anyone give an exemple of when long term access to a variable will result in an error ? I can't come with one.

edit:

I tested with a playground on Xcode 9.2

Upvotes: 4

Views: 441

Answers (1)

Konrad Leszczyński
Konrad Leszczyński

Reputation: 161

It will work in playground - the playground is not a perfect simulator.

Try "New -> Project -> Single View App"
This piece of code will crash (even on simulator) in runtime with something like:

Thread 1: Simultaneous accesses to 0x6000022b4310, but modification requires exclusive access

Upvotes: 1

Related Questions