Converting Swift Decimal128 to-from Int

I have a Realm Sync schema that specifies a field called performance with "bsonType": "decimal". In Swift, that gets turned into a Decimal128.

Sometimes, the value I store in this field is actually an integer.

I have discovered that I can convert from Int to Decimal128 by using Decimal128(integerLiteral: Int64(intValue)) - which feels a bit clumsy, but at least it works.

I have no idea how to turn my Decimal128 value back into an Int. (Except maybe by going via a String… surely not?!)

What is the proper way to convert a Decimal128 value to and from an Int value in Swift?

Thanks!

Not pretty but…

Int(truncating: NSDecimalNumber(decimal: performance.decimalValue))

Note that you could use the new Type Projections feature to convert the Decimal128 into an enum that returns an Int or a Decimal depending on the value.

I’ll be publishing a Dev Hub article on type projections tomorrow – I’ll add the link here when it’s live.

Andrew.

2 Likes

Here’s a link to my new post on Realm-Swift Type Projections: Realm-Swift Type Projections

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.