Reputation: 387
I started Swift today.
I have no idea how to share variables between functions. Does anyone have an idea?
@IBAction func function1(sender : NSButton) {
var variable1 = 1
}
@IBAction func function2(sender: NSButton) {
println(variable1)
}
I googled about this, but I couldn't find the solution.
I'm using Xcode6 beta6.
----EDITED----
The specific thing I wanted to do was the code below.
var files: [AnyObject] = [AnyObject]()
@IBAction func selectFiles(sender : NSButton) {
let openDlg = NSOpenPanel()
openDlg.allowsMultipleSelection = true
openDlg.canChooseFiles = true
openDlg.canChooseDirectories = true
if openDlg.runModal() == NSOKButton{
var files = openDlg.URLs
}
}
@IBAction func startScript(sender: NSButton) {
for var i = 0; i < files.count; i++ {
var fileName:AnyObject = files[i];
println(files[i])
}
}
In fact, I wanted to open a dialog to select files, and log the paths of those files.
No error occurs in this code, but nothing is printed. How can I do so?
Upvotes: 1
Views: 1252
Reputation: 1816
Why are you not declaring variable1
outside and then use it in both of your functions as shown below:
var variable1 = 0
@IBAction func function1(sender : NSButton) {
variable1 = 1
}
@IBAction func function2(sender: NSButton) {
println(variable1)
}
EDIT: Based on the new code you posted, you are doing
var files = openDlg.URLs
Here, you are declaring a local variable and not using your global one.
Remove the var
from here and keep only
files = openDlg.URLs
Upvotes: 1