Reputation: 407
I know that there are already some answers about this, but none of them seem to solve my issue as they talk about variables or constants being identified in other classes, but mine isn't.
Here is my viewcontroller.swift (I have not made code in any other files)
class ViewController: UIViewController, UITextFieldDelegate {
// MARK: Properties
@IBOutlet weak var textFieldA: UITextField!
@IBOutlet weak var textFieldB: UITextField!
@IBOutlet weak var textFieldC: UITextField!
@IBOutlet weak var answerLabel: UILabel!
@IBOutlet weak var answerLabelNegative: UILabel!
@IBOutlet weak var whatEquation: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
textFieldA.delegate = self
textFieldB.delegate = self
textFieldC.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hide the keyboard.
textFieldA.resignFirstResponder()
textFieldB.resignFirstResponder()
textFieldC.resignFirstResponder()
return true
}
// MARK: Actions
@IBAction func solveButton(sender: AnyObject) {
let a:Double! = Double(textFieldA.text!) // textfieldA is UITextField
let b:Double! = Double(textFieldB.text!) // textfieldB is UITextField
let c:Double! = Double(textFieldC.text!) // textFieldC is UITextField
let z: Double = (b * b) + 4 * a * c
answerLabel.text = "Positive equation x = \(-b + (sqrt(z) / 2 * a))"
answerLabelNegative.text = "Negative equation x = \(-b - (sqrt(z) / 2 * a))"
// These conditional statements are used to determine whether a + or a - should be infron of th number
if a < 0 {
let aValue: String = "-"
} else {
let aValue: String = " "
}
if b < 0 {
let bValue: String = "-"
} else {
let bValue: String = " "
}
if c < 0 {
let cValue: String = "-"
} else {
let cValue: String = " "
}
whatEquation.text = "\(aValue)\(a) \(bValue)\(b) \(cValue)\(c)" //This is where the error occurs, on the "whatEquation.text" line
}
}
Upvotes: 0
Views: 139
Reputation: 3878
aValue
, bValue
and cValue
are defined in the if
scope and cannot be accessed outside the if block. You need to define them below your @IBOutlet
definitions (as global variables) so u can use them anywhere in your code.
var aValue: String!
var bValue: String!
var cValue: String!
And in your if block remove the let
when you are assigning the text to the a b and c values.
Upvotes: 0
Reputation: 9825
You're defining aValue
, bValue
and cValue
inside of the if statements so they only exist inside of the if statements where they are defined and aren't visible to your last line where they set the text.
You should change it so they are defined in a scope where your last line can see them.
let aValue = a < 0 ? "-" : " "
let bValue = b < 0 ? "-" : " "
let cValue = c < 0 ? "-" : " "
whatEquation.text = "\(aValue)\(a) \(bValue)\(b) \(cValue)\(c)"
Upvotes: 2