Reputation: 91
I am developing a game in Xcode with Swift.
In my 'SPSwipes.swift' file, a variable is given an initial value. However I have looked all around the internet to find out how to modify that variable in my GameViewController, but I can't find anything. Apparently there is no need to 'import', so how do I access that variable in a different file?
Thanks, Will
Upvotes: 1
Views: 3720
Reputation: 1281
In one file, declare a variable like normal:
var str = "Value2"
In the other file, access the variable like any other:
print(str)
str = "Value2"
Swift variables are global.
Upvotes: 0
Reputation: 227
in one file called otherFile.swift , I have
class otherFile: NSObject {
var str:NSString = "hi"
}
and in the next file I have
println(otherFile().str)
this works, make sure you instantiate the object first
Upvotes: 0
Reputation: 72810
First you have to be sure that the variable has not been declared as private
.
If the file where the variable is declared and the file where you are trying to use the variable are in the same module, then there's nothing special to do - just reference the variable from the other file, and it has to work.
If the variable and the source where you want to use it are in different modules, then the variable must be declared as public
and you have to import the module in the file where you want to access it.
I presume your case is the first. If still doesn't work, it would be good to know how you have defined the variable and how you are trying to access to it (which means, share some code).
Upvotes: 2