2015-06-28 143 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

相关问题