尝试将字符串转换为双精度时出错

Error when trying to convert string to a double

我正在尝试将 Swift 中的字符串转换为双精度值。经过大量研究,我相信这是将我的字符串转换为 Double 的最佳方法。但是现在我收到一个错误,我不知道如何修复。

var purchaseAmount: Double = 200

var cashTendered: Double = 425.45

var changeRequired: Double = 0

var currencyValues = ["100", "50", "20", "10", "5", "2", "1", "0.50", "0.20", "0.10", "0.05"]

import Cocoa

if cashTendered < purchaseAmount {
    println("Not enough cash tendered")
} else {
    changeRequired = cashTendered - purchaseAmount
    for currency in currencyValues {
        var doubleCurrency = (currency as NSString).doubleValue
        var amountOfCurrency = changeRequired / doubleCurrency
        amountOfCurrency = floor(amountOfCurrency)
        changeRequired = changeRequired - (amountOfCurrency * currency)
        changeRequired = round(changeRequired * 100)/100
        println("$\(currency) X \(Int(amountOfCurrency))")
    }
}

错误如下:

我该怎么做才能解决这个问题?

发布代码比图片更容易看,但如果其他方法都失败了,还有 NSNumberFormatter。 NSNumberFormatter 的其他优点是允许您转换两个方向并获得诸如货币之类的良好输出。

首先像下面这样初始化 String 数组:

let currencyValues : [String] = ["100", "50", "20", "10", "5", "2", "1", "0.50", "0.20", "0.10", "0.05"]

但是不需要类型声明,因为 Swift 具有重要特征 Type Interface。但是大多数实践在使用数组时定义类型是很好的。

关于将字符串转换为双精度,您可以使用以下代码:

for currency : String in currencyValues {
   let doubleCurrency = NSNumberFormatter().numberFromString(currency)!.doubleValue
   print(doubleCurrency)
}