Are Swift variables atomic?

前端 未结 6 1262
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 04:19

In Objective-C you have a distinction between atomic and nonatomic properties:

@property (nonatomic, strong) NSObject *nonatomicObject;
@property (atomic, st         


        
6条回答
  •  借酒劲吻你
    2020-11-28 04:56

    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.

提交回复
热议问题