Search code examples
swiftrealm

Realm Swift - data type for currency


I've noticed in this question here Using Realm.io to store money values

that the recommendation is to use a 'long' data type for currency values in Realm for Android/Java.

What would the best recommendation be for Swift? Convert it to an Int by multiplying by a factor based on the currency? At the moment I'm only dealing with a single currency, but this could theoretically change. Precision is obviously important this being a monetary value.


Solution

  • I would recommend using an Int type and then dividing by 100 to convert to cents and multiplying by 100 to store in the Realm. The only downside is you won't be able to filter on the moneyWithCents value.

    class HasMoney: Object {
        private dynamic var money:Int = 0
    
        var moneyWithCents: Double {
            get {
                return money/100.0
            }
            set {
                money = newValue * 100
            }
        }
    }