DanielAsking
DanielAsking

Reputation: 333

Using swift func vars in other functions

How can I access a variable in a function which is initialized within another function? Is it even possible?

e.g..:

@IBAction func myButtonPressed(sender : AnyObject) {
    var i = 1
}

how can i access i to increment it if I press another button and give this value to an IBOutlet?

So something like:

@IBOutlet var myLabel : UILabel = nil

@IBAction func mySecondButtonPressed(sender : AnyObject) {
    i = i + 1
    myLabel.text = String(i)
}

Upvotes: 1

Views: 215

Answers (1)

Malcolm Jarvis
Malcolm Jarvis

Reputation: 228

You'll need to declare i as an instance variable.

var i = 0

@IBAction func myButtonPressed(sender : AnyObject) {
    i = 1
}

@IBAction func mySecondButtonPressed(sender : AnyObject) {
    i = i + 1
    myLabel.text = String(i)
}

Upvotes: 3

Related Questions