2016-06-07 50 views
0

我是新來這個網站,請裸露在我身邊。 我想在Swift中構建一個簡單的計算器,但我不知道如何或爲什麼我得到錯誤(「字符串類型的值沒有成員類型Int」)或如何解決它。這是到目前爲止我的代碼:Swift代碼錯誤:類型字符串的值有沒有成員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. 
} 

}

哪兒我去錯了嗎?

+2

不要濫用武力展開操作符(''!)這樣的。 – Alexander

回答

3

相反的:

firstNumber = calculatorDisplay.text?.Int()! 

你想要的東西,如:

if let text = calculatorDisplay.text? { 
    firstNumber = Int(text)! 
} 

或者,如果你想住在邊緣:

firstNumber = Int(calculatorDisplay.text!)! 
+3

由於您正在學習Swift,因此我會鼓勵您在不使用'!'的情況下編寫所有代碼(瞭解'如果let','guard let'和可選的鏈接代替)。 –

+0

或'calculatorDisplay.text.flatMap {Int($ 0)}''如果你想得到時髦的 – Hamish

+0

@ originaluser2 ...不要給他們點子......:p – Alexander

1

有一個在沒有Int()方法String類型。

要轉換IntString,試試這個:

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 
相關問題