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
Original Code:
int sum = 0;
x = 1;
for (int i = 0; i < 100; i++) {
sum += x;
}
==================
Need to replace with :
var sum = 0
public let x = 1
for i in 0..<100 {
sum += x;
}
Please let me know if any confusion is there in this.
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++.
I will expand on @potatoswatter's (excellent) comments . There are a couple of misunderstandings here
Volatile
has nothing to do with accessibilityVolatile
is not a sufficient construct here since it is ensures read
consistency to threads when they access that variable. Your use case is involving mutations
to x
and thus requires synchronization
that is a more thorough concurrency construct. This is a moderately advanced concept and is not in the wheelhouse of swift
. If you want to use x from anywhere, then you need to write this variable like this, var x = 0
Updated code :
Let us know if any confusion here.