Search code examples
swiftuibuttonswift-playground

Issue with using variables inside a class function (Swift Playgrounds)


I want to create a function so when a button gets pressed, the content of a variable changes. The function does get called, but I can't use any external variables inside it.

This is the code I'm having trouble with:

class Responder: NSObject {
    func pressed(sender: UIButton) {
        // Can't change the value of "a" here
    }
}

var a: Int = 0

let responder = Responder()
let bt = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: 200.0, height: 200.0))
bt.addTarget(responder, action: #selector(Responder.pressed), for: .touchUpInside)

What can I do to make this work?


Solution

  • It does work. You can change the value of a in pressed. I added code to your pressed method, as follows:

    import UIKit
    import PlaygroundSupport
    
    class Responder: NSObject {
        func pressed(sender: UIButton) {
            a = a+1
            print(a)
        }
    }
    var a: Int = 0
    
    let responder = Responder()
    let bt = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: 200.0, height: 200.0))
    bt.addTarget(responder, action: #selector(Responder.pressed), for: .touchUpInside)
    PlaygroundPage.current.liveView = bt
    

    The button appears, and each time I tap it, a higher number is printed out, starting with 1 (because a was 0 to start with). This proves that your code can change a.