Swift 3 中的十进制到双精度转换 [英] Decimal to Double conversion in Swift 3

查看:26
本文介绍了Swift 3 中的十进制到双精度转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个项目从 Swift 2.2 迁移到 Swift 3,并且我正在尝试尽可能摆脱旧的 Cocoa 数据类型.

I'm migrating a project from Swift 2.2 to Swift 3, and I'm trying to get rid of old Cocoa data types when possible.

我的问题是:将 NSDecimalNumber 迁移到 Decimal.

My problem is here: migrating NSDecimalNumber to Decimal.

我曾经在 Swift 2.2 中以两种方式将 NSDecimalNumber 桥接到 Double:

I used to bridge NSDecimalNumber to Double both ways in Swift 2.2:

let double = 3.14
let decimalNumber = NSDecimalNumber(value: double)

let doubleFromDecimal = decimalNumber.doubleValue

现在,切换到 Swift 3:

let double = 3.14
let decimal = Decimal(double)

let doubleFromDecimal = ???

decimal.doubleValue 不存在,也不存在 Double(decimal),甚至不存在 decimal as Double...我想出的唯一黑客是:

decimal.doubleValue does not exist, nor Double(decimal), not even decimal as Double... The only hack I come up with is:

let doubleFromDecimal = (decimal as NSDecimalNumber).doubleValue

但是试图摆脱NSDecimalNumber是完全愚蠢的,并且不得不偶尔使用它......

But that would be completely stupid to try to get rid of NSDecimalNumber, and have to use it once in a while...

好吧,要么我错过了一些明显的东西,请原谅我浪费了你的时间,要么我认为有一个漏洞需要解决......

Well, either I missed something obvious, and I beg your pardon for wasting your time, or there's a loophole needed to be addressed, in my opinion...

预先感谢您的帮助.

编辑:没有更多关于 Swift 4 的主题.

Edit : Nothing more on the subject on Swift 4.

编辑:没有更多关于 Swift 5 的主题.

Edit : Nothing more on the subject on Swift 5.

推荐答案

NSDecimalNumberDecimal 桥接

Swift 覆盖到 Foundation 框架提供了 Decimal结构,它连接到 NSDecimalNumber 类.十进制值类型提供与 NSDecimalNumber 相同的功能引用类型,两者在 Swift 代码中可以互换使用与 Objective-C API 交互.这种行为类似于Swift 将标准字符串、数字和集合类型桥接到它们的相应的基础课程.Apple 文档

The Swift overlay to the Foundation framework provides the Decimal structure, which bridges to the NSDecimalNumber class. The Decimal value type offers the same functionality as the NSDecimalNumber reference type, and the two can be used interchangeably in Swift code that interacts with Objective-C APIs. This behavior is similar to how Swift bridges standard string, numeric, and collection types to their corresponding Foundation classes. Apple Docs

但与其他一些桥接类型一样,某些元素缺失.

but as with some other bridged types certain elements are missing.

要重新获得功能,您可以编写扩展程序:

To regain the functionality you could write an extension:

extension Decimal {
    var doubleValue:Double {
        return NSDecimalNumber(decimal:self).doubleValue
    }
}

// implementation
let d = Decimal(floatLiteral: 10.65)
d.doubleValue

这篇关于Swift 3 中的十进制到双精度转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆