Swift Code Error: Value of type String has no member Int
12,617
Solution 1
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!)!
Solution 2
There is no Int()
method in the String
type.
To convert an Int
to String
, try this:
guard let text = calculatorDisplay.text else {
//the CalculatorDisplay has no text, deal with it accordingly
}
guard let firstNumber = Int(text) else {
//the CalculatorDisplay has text, but it's not a valid Int
}
//use firstNumber
Author by
Geniouse
Updated on June 15, 2022Comments
-
Geniouse almost 2 years
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?