我知道已经有一些关于此问题的答案,但是他们似乎都没有解决我的问题,因为他们谈论的是在其他类中识别的变量或常量,但我的不是。
这是我的viewcontroller.swift(我还没有在任何其他文件中创建代码)
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
}
}
答案 0 :(得分:2)
您在if语句中定义了aValue
,bValue
和cValue
,因此它们只存在于定义它们的if语句中,并且不是在他们设置文本的最后一行可见。
您应该更改它,以便在最后一行可以看到它们的范围内定义它们。
let aValue = a < 0 ? "-" : " "
let bValue = b < 0 ? "-" : " "
let cValue = c < 0 ? "-" : " "
whatEquation.text = "\(aValue)\(a) \(bValue)\(b) \(cValue)\(c)"
答案 1 :(得分:0)
aValue
,bValue
和cValue
在if
范围内定义,无法在if块之外访问。您需要在@IBOutlet
定义下面定义它们(作为全局变量),以便您可以在代码中的任何位置使用它们。
var aValue: String!
var bValue: String!
var cValue: String!
在if块中,当您将文本分配给a b和c值时,删除let
。