[swift-evolution] Still Missing: Fixed Decimal Numerical Type.

Brent Royal-Gordon brent at architechies.com
Wed Mar 30 19:21:54 CDT 2016


> var depositPromille: Decimal(10,3) = -1234.56
> typealias  Money = Decimal(20,2) 

There is no mechanism to parameterize types like this. (Specifically, you can only parameterize a generic type with types, not integers or other values.) That makes this a fairly large effort—certainly not impossible, but more than just writing some code and putting it in the standard library. "As soon as possible" will still be quite a ways away, and may not even come in this Swift version.

As a stopgap, use NSDecimal (which is not fixed, but does provide decimal arithmetic) or write your own Money struct:

	struct Money {
		private var cents: Int
		
		init(_ value: Int) {
			cents = value * 100
		}
		
		init(cents: Int) {
			self.cents = cents
		}
		
		init(approximating value: Double) {
			cents = Int(value * 100)
		}
	}
	
	extension Int {
		init(approximating value: Money) {
			self = value.cents / 100
		}
		init(cents value: Money) {
			self = value.cents
		}
	}
	
	extension Double {
		init(approximating value: Money) {
			self = Double(value.cents) / 100
		}
	}
	
	extension Money: StringLiteralConvertible {
		// or FloatLiteralConvertible if you think you can get away with it
		...
	}
	
	extension Money: Hashable, Comparable, CustomStringConvertible {
		...
	}
	
	func + (lhs: Money, rhs: Money) -> Money { return Money(cents: lhs.cents + rhs.cents) }
	func * (lhs: Money, rhs: Int) -> Money { return Money(cents: lhs.cents * rhs) }
	// etc.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list