2015-06-28 144 views
1

代碼以綠色高亮顯示的Xcode中(線程1:EXC_BAD_INSRTUCTION)致命錯誤 - 我知道原因,但不知道如何解決它

amountDueLabel.text = String(HomeViewController().getAllowanceDue()) 

功能getAllowanceDue()

func getAllowanceDue() -> Int{ 
    var allowance = allowanceTextField.text.toInt() 
    return allowance! 
} 

非常感謝!

悠着點了我 - 我在iOS開發初學者

回答

1

在斯威夫特不像Objective C中,你必須明確地讓編譯器知道一個變量可以在未來的「零」的標記該變量作爲可選(?)。

toInt()方法也返回'可選的整數值',這意味着toInt()方法也可以返回'nil'值,以防它不能將提供的字符串值轉換爲整數值。

在這裏,您將展開可選的Int值與allowance!。但在解包可選值之前,您必須檢查可選值是否爲'nil'。

func getAllowanceDue() -> Int { 
    if let allowance = anotherString.toInt() { 
     return allowance 
    } 
    return -1 
} 

通過我們實際使用的斯威夫特Optional Binding概念檢查可選是否包含值檢查if let allowance = anotherString.toInt()

+0

@richbrz:此解決方案適合您嗎? – tek3

+0

是的,我真的很感謝及時的答覆。 – richbrz

相關問題