Decimal to Double conversion in Swift 3

后端 未结 7 1440
春和景丽
春和景丽 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:15

    NSDecimalNumber and Decimal are bridged

    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
    
    0 讨论(0)
提交回复
热议问题