我正在尝试在 Swift 中构建一个简单的计算器,但我无法弄清楚我如何或为什么会收到错误(“String 类型的值没有成员类型 Int”)或如何修复它。到目前为止,这是我的代码:
class ViewController: UIViewController {
var isTypingNumber = false
var firstNumber = Int!()
var secondNumber = Int!()
var operation = ""
@IBOutlet weak var calculatorDisplay: UILabel!
@IBAction func acButtonTapped(sender: AnyObject) {
}
@IBAction func number7Tapped(sender: AnyObject) {
let number7 = sender.currentTitle
if isTypingNumber{
calculatorDisplay.text = calculatorDisplay.text! + number7!!
}else{
calculatorDisplay.text = number7
isTypingNumber = true
}
}
@IBAction func divideTapped(sender: AnyObject) {
isTypingNumber = false
firstNumber = calculatorDisplay.text?.Int()! **//Error: Value of type 'String' has no member 'Int'**
operation = sender.currentTitle!!
}
@IBAction func equalsTapped(sender: AnyObject) {
isTypingNumber = false
var result = 0
secondNumber = calculatorDisplay.text?.Int()! **//Error: Value of type 'String' has no member 'Int'**
if operation == "+" {
result = firstNumber + secondNumber
} else if operation == "-" {
result = firstNumber - secondNumber
}else if operation == "X" {
result = firstNumber * secondNumber
}else if operation == "÷"{
result = firstNumber / secondNumber
}
calculatorDisplay.text = "\(result)"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
firstNumber = 0
secondNumber = 0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
Run Code Online (Sandbox Code Playgroud)
}
我哪里做错了?
代替:
firstNumber = calculatorDisplay.text?.Int()!
Run Code Online (Sandbox Code Playgroud)
你想要这样的东西:
if let text = calculatorDisplay.text? {
firstNumber = Int(text)!
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您想生活在边缘:
firstNumber = Int(calculatorDisplay.text!)!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11876 次 |
| 最近记录: |