[英]Fatal error in Xcode - I know the cause but don't know how to fix it
code highlighted in green by Xcode (Thread 1: EXC_BAD_INSRTUCTION) Xcode以绿色突出显示的代码(线程1:EXC_BAD_INSRTUCTION)
amountDueLabel.text = String(HomeViewController().getAllowanceDue())
the function getAllowanceDue()
函数
getAllowanceDue()
func getAllowanceDue() -> Int{
var allowance = allowanceTextField.text.toInt()
return allowance!
}
thank you so much! 非常感谢!
Go easy on me - I am a beginner in iOS development 轻松一点-我是iOS开发的初学者
In Swift unlike Objective C, you have to explicitly let the compiler know that a variable can be 'nil' in future by marking that variable as optional (?). 在Swift中,与Objective C不同,您必须通过将变量标记为可选(?)来明确让编译器知道该变量将来可能为“ nil”。
toInt()
method also returns an 'optional Integer value' which means toInt()
method can also return 'nil' value in case it is not able to convert the supplied string value to integer value. toInt()
方法还返回一个“可选的整数值”,这意味着如果toInt()
方法无法将提供的字符串值转换为整数值,则它也可以返回“ nil”值。
Here you are unwrapping the optional Int value with allowance!
在这里,您可以使用
allowance!
展开可选的Int值allowance!
. 。 But before unwrapping the optional value you must check if the optional value is not 'nil'.
但是在解开可选值之前,您必须检查可选值是否不是'nil'。
func getAllowanceDue() -> Int {
if let allowance = anotherString.toInt() {
return allowance
}
return -1
}
By checking if let allowance = anotherString.toInt()
we are actually using concept of Optional Binding in Swift to check whether optional contains a value. 通过检查
if let allowance = anotherString.toInt()
我们实际上在Swift中使用了Optional Binding的概念来检查optional是否包含一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.