4

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

  • 5
    It crashes with "Simultaneous accesses to 0x1003b8260" in my Xcode 9.2 and 9.3beta. – Btw, "undefined/unsafe behavior" does not mean that the result *has* to be wrong. – Martin R Jan 26 '18 at 15:46
  • 3
    The behavior depends upon your project's "Exclusive access to memory" setting in the target's build settings, as well as potentially whether you do debug or release build. – Rob Jan 26 '18 at 15:53
  • 2
    See "Exclusive Access to Memory" in latter part of WWDC 2017 [What's New in Swift](https://developer.apple.com/videos/play/wwdc2017/402/) video for examples where problems can arise. – Rob Jan 26 '18 at 16:01
  • 2
    Looks like playgrounds have dynamic exclusivity checks disabled by default. If you try it in an actual project (w/ default build settings), dynamic enforcement will catch the exclusive access violation, as Martin says. – Hamish Jan 26 '18 at 16:14

1 Answers1

1

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