xcode:需要将字符串转换为double并返回字符串

时间:2015-12-09 23:27:58

标签: xcode swift double

这是我的代码行。

budgetLabel.text = String((budgetLabel.text)!.toInt()! - (budgetItemTextBox.text)!.toInt()!)

代码有效,但当我尝试在文本框中输入浮动值时程序崩溃。我假设字符串需要转换为float / double数据类型。当我尝试这样做时,我一直都会遇到错误。

3 个答案:

答案 0 :(得分:2)

Swift 2 中有新的可用初始化程序,允许您以更安全的方式执行此操作,Double("")在传递"abc"字符串的情况下返回可选项可用的初始值设定项将返回nil,因此您可以使用optional-binding来处理它,如下所示:

let s1 = "4.55"
let s2 = "3.15"

if let n1 = Double(s1), let n2 = Double(s2) {
   let newString = String( n1 - n2)
   print(newString)
}
else {
  print("Some string is not a double value")
} 

如果你使用的是 Swift< 2 ,然后老路是:

var n1 = ("9.99" as NSString).doubleValue  // invalid returns 0, not an optional. (not recommended)

// invalid returns an optional value (recommended)
var pi = NSNumberFormatter().numberFromString("3.14")?.doubleValue

答案 1 :(得分:1)

修正:添加了对选项的正确处理

let budgetLabel:UILabel = UILabel()
let budgetItemTextBox:UITextField = UITextField()
budgetLabel.text = ({
     var value = ""
     if let budgetString = budgetLabel.text, let budgetItemString = budgetItemTextBox.text
     {
          if let budgetValue = Float(budgetString), let budgetItemValue = Float(budgetItemString)
          {
               value = String(budgetValue - budgetItemValue)
          }
     }
     return value
})()

答案 2 :(得分:0)

您需要使用if let。在swift 2.0中,它看起来像这样:

if let
    budgetString:String = budgetLabel.text,
    budgetItemString:String = budgetItemTextBox.text,
    budget:Double = Double(budgetString),
    budgetItem:Double = Double(budgetItemString) {
        budgetLabel.text = String(budget - budgetItem)
} else {
    // If a number was not found, what should it do here?
}
相关问题