Nandhu Nandhu - 1 month ago 4
Swift Question

I am stuck in an xcode 8 situation

I am currently making a calculator, and I am using Swift, with XCode 8. I have already defined a variable, but when I want to connect it to my button and text field, it says use of unresolved identifier. Can anyone help me?

Screenshot:

enter image description here

Answer

Your sum variable is defined inside the Solve function scope, so it can only be used inside that scope. You have to make your variable global (i.e. inside the UIViewController scope) for it to be visible inside all the functions.

  • Define var sum outside the function, under Oranges.

    class ViewController : UIViewController {
        @IBOutlet weak var Apples :UITextField!
        @IBOutlet weak var Oranges :UITextField!
        var sum : String!
    
        @IBAction func Solve(_ sender: AnyObject)
        {
            var apples = Int(Apples.text!)
            var oranges = Int(Oranges.text!)
            sum = String(oranges! + apples!)
        }
    
    }
    
Comments