How does SwiftData and Decimal Works?

Hi! Not sure if this is a swift data or more a Decimal in general type of question.

What's going on:

I have a SwiftUI app using SwiftData, I have persisted a Model with a property "reducedPrice" of type Decimal. It's stores correctly the value. Now, I have read the value during automated tests and tried comparing the values:

let reducedPrice = model.reducedPrice // swift data property
let target = Decimal(4.98) // expected target value to compare to swift data value.

Now if I just print the result of the comparison between those 2 I get a false result.

print(reducedPrice == target) //output : false

The swift data model was populated from a direct copy of another struct that comes from an JSON import using Codable+CodingKeys (I used Decimal type).

What I expected:

I expected it to be true.

Debug Observations

I did noticed that on the variable inspector both had the same magnitudes but in reality the mantissa are different. I'm attaching a screenshot.

My Theory

They are different just because something under SwiftData stores different way the decimal as in comparison on how I am creating the Decimal for the comparison inside the automated tests.

My question

Is this expected behavior? Any suggestion on best practices on how to handle this?

Thank you in advance any relevant guidance is very appreciated!

Answered by in
Accepted Answer

I don’t have an answer to any of your specific questions, but my general advice here is that you avoid Decimal when modelling currency values. Rather, use an Int count of that currency’s minimum unit. For example, for USD that would be cents, and for JPY that’d be yen. That’s easy to understand and it avoids all the sharp edges surrounding Decimal.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

How does SwiftData and Decimal Works?
 
 
Q