ios - 在 Swift 中更改类型

标签 ios swift

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

这是我的代码:

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!)!

说:

"Cannot invoke 'init' with an argument of type '@!value String!'



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

任何帮助表示赞赏!

最佳答案

试试这个:

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

关于ios - 在 Swift 中更改类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61858482/

相关文章:

xcode - 设备上的 iOS 版本与 Xcode 支持的版本不匹配

ios - 是否可以在 iOS 14 WidgetKit 中动态更新/更改布局(例如 View 数量)?

从枚举中提取 Swift 2 值

swift - SceneKit 基础知识

ios - 为什么我的按钮显示但无法点击?

ios - 在状态栏下方获取自动布局

ios - 应用过滤器(AVAudioUnitEQ)后保存音频文件并最终将其保存为mp3?

ios - ejabberd 501 功能未实现

swift - 如何从点击中获取 SKSpriteNode 子类对象

ios - .reloadData() 没有重新创建可见单元格或内存中的单元格?