Yesterday Apple talked about exclusivity enforcement in Swift 5, in a post. No this is not some exclusive feature or patenting of some sort. This idea is on how variables in a Swift program access memory. Swift is the programming language used for developing Apple apps.
What is exclusivity enforcement?
The Swift 5 release allows runtime checks on “Exclusive Access to Memory”. This further adds to Swift showing that it is a ‘safe language’. For memory safety to take place, Swift needs exclusive access to a variable and modify it. This means that the variable can be accessed only with the same name when it is being modified as particular arguments. A programmer’s intention in case of exclusivity violations is often ambiguous in Swift. So, to protect against it and to allow the safety features, exclusivity enforcement was introduced in Swift 4.
In Swift 4, both compile-time and run-time enforcement was available, the latter being available only in debug builds. Some of the holes in exclusivity enforcement are patched in Swift 5 by changing the language model. So runtime exclusivity enforcement is enabled by default in Release builds.
This can impact Swift projects in two ways:
- Violation of Swift exclusivity rules causing a runtime trap
- Overhead due to memory access checks can degrade performance slightly
Why exclusivity enforcement?
This enforcement is done mainly to enforce memory safety in Swift.
- It eliminates dangerous interactions in Swift programs which involves mutable states
- Enforcement gets rid of unspecified behavior rules from Swift
- It is mandatory to maintain ABI stability
- In addition to protecting memory safety, this enforcement helps in optimizing performance
- The exclusivity rules give programmers the control to move only types
Even though the memory problem is a rare occurrence, addressing it early on improves Swift a bit. A comment on Hacker news says: “The benefit being that you only have to deal with this issue rarely, rather than all the time with manual memory management.”