xcode beta bridgeToObjectiveC替代?

时间:2014-08-14 20:35:11

标签: objective-c xcode swift xcode6

我目前正在制作一个计算器应用程序,我需要使用bridgeToObjectiveC代码,但在xcode 6的当前测试版中已不再可用。这是我需要编写的代码:

 @IBAction func btnAdditionCalculate(sender: AnyObject) {

    let firstNumber = txtAdditionFirst.text.bridgeToObjectiveC().floatValue
    let secondNumber = txtAdditionSecond.text.bridgeToObjectiveC().floatValue
    let answer = firstNumber + secondNumber

    var answerFormat: NSString = NSString(format: "%0.0f", answer)

    labelAdditionAnswer.text = " \(answerFormat)"

}

我知道我需要使用NSString并尝试这样做,但它不起作用:

@IBAction func btnAdditionCalculate(sender: AnyObject) {

    let firstNumber = (txtAdditionFirst.text as NSString).floatValue
    let secondNumber = (txtAdditionSecond.text as NSString).floatValue

    let answer = firstNumber + secondNumber

    var answerFormat: NSString = NSString(format: "%0.0f", answer)

    labelAdditionAnswer.text = " \(answerFormat)"

}

感谢您的帮助

编辑8/15

当我在iOS模拟器上运行代码时,应用程序加载并且我能够将数字放入数字1和数字2插槽中,但是当我按下计算xcode时突出显示let firstNumber行并说出主题1:EXC_BAD_INSTRUCTION和这是我收到的错误消息:

2014-08-15 16:14:53.019 Innovative Calculator p1[578:8032] Can't find keyplane that                          supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default
2014-08-15 16:14:55.425 Innovative Calculator p1[578:8032] Can't find keyplane that supports type 8 for keyboard iPhone-Portrait-DecimalPad; using 1425143906_Portrait_iPhone-Simple-Pad_Default
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) 

1 个答案:

答案 0 :(得分:0)

如果您的代码在let firstNumber = ...上停止并且使用nil可选转换,则表示您错误地认为txtAdditionFirsttextAdditionFirst.text不是nil。 UITextField保证.text永远不会为零,所以最好的办法就是你没能在Interface Builder中连接txtAdditionFirst

您可以通过检查变量定义来查看它是否被填充或在行上方设置断点并查看它是否为零来验证这一点。

如果你有一个有效的理由让变量为零,你可以选择这样做:

// The long way (mutable)
var firstNumber:Float = 0
if let value = textField?.text {
    firstNumber = (value as NSString).floatValue
}

// The short way (not mutable)
let firstNumber = (textField?.text? as NSString?)?.floatValue ?? 0.0

第一种方法最初将数字设置为零,然后使用可选链接来测试textField和textField.text是否为nil。第二种方法使用可选的链接整个方式来获得一个可选的浮点值,然后解包它,如果不是nil或回落到0。