I'm trying to build a simple calculator in Swift but i can't figure how or why i'm getting the error ("Value of type String has no member type Int") or how to fix it. This is my code so far:
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.
}
}
Where did i go wrong?
Instead of:
firstNumber = calculatorDisplay.text?.Int()!
You want something like:
if let text = calculatorDisplay.text? {
firstNumber = Int(text)!
}
Or if you want to live on the edge:
firstNumber = Int(calculatorDisplay.text!)!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With