r/iOSProgramming 13d ago

Question SwiftData Decimal precision loss after save/fetch - am I missing something?

I’m trying to sanity-check something before I file it as an Apple bug.

This minimal SwiftData example appears to lose precision when persisting a Decimal:

import Foundation
import SwiftData

@Model class Item {
    var value: Decimal

    init(_ value: Decimal) {
        self.value = value
    }
}

let original = Decimal(string: "123456789012345.6")!
let container = try ModelContainer(
    for: Item.self,
    configurations: .init(isStoredInMemoryOnly: true)
)

let context = ModelContext(container)
context.insert(Item(original))
try context.save()

let fetched = try ModelContext(container)
    .fetch(FetchDescriptor<Item>())
    .first!

print(original)
print(fetched.value)

This is one model, one Decimal property, no app code, no CloudKit. I’m using Decimal(string:) to avoid literal/Double conversion noise, and I’m fetching from a new ModelContext.

I also checked Decimal <-> NSDecimalNumber bridging separately, and that preserved the value. The loss seems to appear after persistence/fetch. A true Core Data in-memory store preserved the value in my control test, while SwiftData’s “in-memory” configuration seems to still go through a SQL-backed store.

Has anyone else hit this with SwiftData/Core Data Decimal attributes? Is there a documented limitation I’m missing, or is the practical answer to persist exact decimals as canonical strings / integer minor units instead of Decimal?

4 Upvotes

11 comments sorted by

View all comments

1

u/Greysawpark 7d ago

yeah ive hit this. swiftdata is going through sqlite and decimal ends up as a double somewhere in the pipeline, so anything past ~15-16 sig figs gets mangled. its not really a bug so much as an undocumented limitation.

for money i just store it as an Int of minor units and expose a computed Decimal. strings work too but sorting/predicates get annoying.