How to declare volatile variables in Swift

后端 未结 4 2037
醉梦人生
醉梦人生 2021-02-19 07:57

I want to convert to Swift from Objective-C code like following;

int sum = 0;
x = 1;
for (int i = 0; i < 100; i++) {
    sum += x;
}

x is ac

4条回答
  •  Happy的楠姐
    2021-02-19 08:10

    There is currently no equivalent to volatile in Swift.

    In Swift you have access to more potent means of expressing global synchronicity of values than the volatile keyword - which does not provide any kind of atomicity guarantees, and must be used with locks to establish critical sections. For example, you might choose locks to synchronize read and write access to a variable. You might choose to use an MVar to indicate that a variable should only have 1 possible valid state across multiple threads.

    Or you might choose to simply not express the problem in Swift. If you're looking for the exact behavior of a volatile variable (which, in your situation, sounds unlikely), stick with C and C++.

提交回复
热议问题