【问题标题】:Change Type in Swift在 Swift 中更改类型
【发布时间】:2020-09-03 14:17:46
【问题描述】:

我是 Swift 的新手(隔离学习),并且正在跟随 YouTube 视频创建一个总价应用程序。我在将字符串更改为双精度类型时遇到了问题,基本上是接受输入并将其转换为双精度类型,以便我可以用它进行数学运算。

这是我的代码:

import UIKit


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBOutlet weak var pricetxt: UITextField!
    @IBOutlet weak var taxtxt: UITextField!
    @IBOutlet weak var totalpricelbl: UILabel!

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func Calculate(sender: AnyObject) {
        let price = Double(pricetxt.text!)!
        let tax = Double(taxtxt.text!)!

        let totalsalestax = price * tax
        let totalprice = price + totalsalestax
        totalpricelbl.text = "$\(totalprice)"
    }

}

这两行出现错误:

let price = Double(pricetxt.text!)!
let tax = Double(taxtxt.text!)!

说:

“不能使用'@!value String!'类型的参数调用'init'!

在我的 Mac 10.9.5 上运行 XCode 是 6.2 我知道这些都是旧的,但我无法升级我的笔记本电脑。

感谢任何帮助!

【问题讨论】:

  • 您是否已将文本字段和标签正确连接到情节提要中的 IBOutlet?
  • 什么版本的 Swift?
  • @JoakimDanielson 是的!所有字段都正确连接
  • @elliott-io 我正在使用此链接检查 stackoverflow.com/questions/30790188/… 的版本,但是当我在 Xcode 6.2 上运行它时,没有出现“swift language”菜单。我猜是因为它太旧了?
  • 请注意,从那时起 Swift 发生了很大变化。学习 Swift 1.x 可能会浪费时间。 Xcode 6 在当时也确实存在问题。你的机器是什么?

标签: ios swift


【解决方案1】:

试试这个:

let price = (pricetxt.text! as NSString).doubleValue
let tax = (taxtxt.text! as NSString).doubleValue

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-16
    • 2018-10-07
    • 2019-05-09
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 2021-12-04
    相关资源
    最近更新 更多