xcode:需要将字符串转换为双精度并返回字符串

xcode: need to convert strings to double and back to string

这是我的代码行。

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

代码有效,但是当我尝试向文本框输入浮动值时,程序崩溃了。我假设字符串需要转换为 float/double 数据类型。当我尝试这样做时,我不断收到错误。

您需要使用 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?
}

Swift 2 中有新的可失败初始化器,允许您以更安全的方式执行此操作,Double("") returns在像传入 "abc" 字符串这样的情况下,可选项是可选的,可失败的初始化程序将 return 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

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

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
})()