Decimal to Double conversion in Swift 3

后端 未结 7 1456
春和景丽
春和景丽 2020-12-29 01:42

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.

My problem is

7条回答
  •  心在旅途
    2020-12-29 02:06

    You are supposed to use as operator to cast a Swift type to its bridged underlying Objective-C type. So just use as like this.

    let p = Decimal(1)
    let q = (p as NSDecimalNumber).doubleValue
    

    In Swift 4, Decimal is NSDecimalNumber. Here's citation from Apple's official documentation in Xcode 10.

    Important

    The Swift overlay to the Foundation framework provides the Decimal structure, which bridges to the NSDecimalNumber class. For more information about value types, see Working with Cocoa Frameworks in Using Swift with Cocoa and Objective-C (Swift 4.1).

    There's no NSDecimal anymore. There was confusing NSDecimal type in Swift 3, but it seems to be a bug. No more confusion.

    Note

    I see the OP is not interested in Swift 4, but I added this answer because mentioning only about (outdated) Swift 3 made me confused.

提交回复
热议问题