Swift Error: Cannot find an initializer for type 'Double' that accepts an argument list of type '(String)'

Swift Error: Cannot find an initializer for type 'Double' that accepts an argument list of type '(String)'

我正在尝试从标记为 'temperatureTextField' 的文本字段中获取数据并将其分配给 't',这是一个 Double。理想情况下,用户应该向 temperatureTextField 添加一个数字值。

这是我的方法:

@IBOutlet weak var temperatureTextField: UITextField!

@IBAction func convert(sender: AnyObject) {
    let t = Double(temperatureTextField.text!)
    let tempM = TemperatureModel(temp: t!)
    temperatureTextField.text = String(tempM.toCelsius())
}

红色感叹号来自行"let t = Double(temperatureTex...)"

您可能正在使用 Xcode 6,因此 Swift 1.2,但 Double 的字符串初始值设定项仅在 Swift 2 (Xcode 7) 中可用。

你总是可以使用 NSString 的 doubleValue 属性:

let t = (temperatureTextField.text! as NSString).doubleValue

但我建议尽快使用 Xcode 7 和 Swift 2。

正如 Eric 所建议的,我 运行 进入这个问题是因为我 运行 是 xcode 的过时版本。 这是我的代码看起来喜欢的样子,以防万一有人遇到麻烦而无法更新:

let t = (inputText.text! as NSString).doubleValue
let tempModel = TemperatureModel(temp: t)
inputText.text = "\(tempModel.toCelsius())"