Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Accessing Variables Outside a IBAction | Swift

I am working on a little side project for fun and I am trying to access "inputAC" and "inputB" outside the IBAction to gain access to the numbers from the text fields.

@IBOutlet weak var display: UILabel!
@IBOutlet weak var textFieldAC: UITextField!
@IBOutlet weak var textFieldB: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


    @IBAction func checkNum() {
        var inputAC: Int
        var inputB: Int
        inputAC = textFieldAC.text.toInt()!
        inputB = textFieldB.text.toInt()!
    }
   // Trying to access right here
    var ac: Int = inputAC
    var b: Int = inputB

    func isCommon (#numOne: Int, numTwo: Int) -> Int? {
        if numOne * numTwo == ac && numOne + numTwo == b {
            return true
        } else {
            return nil
        }
    }

    func checkNumbers() {
        let range = 0...b
        var numTwo = 0
        for numOne in range {
            numTwo = b-numOne
            if let result = isCommon(numOne: numOne, numTwo: numTwo) {
                println("Success | \(numOne) and \(numTwo) Work")
                display.text = "Success | \(numOne) and \(numTwo) Work"
                break
            } else {
                println("Failure - \(numOne) and \(numTwo) Does NOT Work")
            }
        }
    }

How would I go about doing this?

Ozzie

1 Answer

You cannot access variables outside methods.

First, if you need to use those variables somewhere else besides your IBAction, it would make sense then to declare those variables as properties.

Just declare them below the IBOutlets (but don't assign them a value!)

Just do it like this:

var ac: Int
var b: Int

You can then remove the declaration from the IBAction method.