Are Swift variables atomic?

It’s very early to assume as no low-level documentation is available, but you can study from assembly. Hopper Disassembler is a great tool.

@interface ObjectiveCar : NSObject
@property (nonatomic, strong) id engine;
@property (atomic, strong) id driver;
@end

Uses objc_storeStrong and objc_setProperty_atomic for nonatomic and atomic respectively, where

class SwiftCar {
    var engine : AnyObject?    
    init() {
    }
}

uses swift_retain from libswift_stdlib_core and, apparently, does not have thread safety built in.

We can speculate that additional keywords (similar to @lazy) might be introduced later on.

Update 07/20/15: according to this blogpost on singletons swift environment can make certain cases thread safe for you, i.e.:

class Car {
    static let sharedCar: Car = Car() // will be called inside of dispatch_once
}

private let sharedCar: Car2 = Car2() // same here
class Car2 {

}

Update 05/25/16: Keep an eye out for swift evolution proposal https://github.com/apple/swift-evolution/blob/master/proposals/0030-property-behavior-decls.md – it looks like it is going to be possible to have @atomic behavior implemented by yourself.

Leave a Comment