Skip to content

Instantly share code, notes, and snippets.

@RoyalIcing
Created March 31, 2016 00:18
Show Gist options
  • Save RoyalIcing/4a1521b27b53512c8858598c33b83728 to your computer and use it in GitHub Desktop.
Save RoyalIcing/4a1521b27b53512c8858598c33b83728 to your computer and use it in GitHub Desktop.
//: Types for currency conversion
// https://www.natashatherobot.com/swift-money-phantom-types/
import Foundation
struct Money {
enum Currency {
case GBP, EUR, USD
}
let amount: NSDecimalNumber
let currency: Currency
}
extension Money.Currency {
var singleInEUR: NSDecimalNumber {
// From http://www.xe.com/currencycharts
switch self {
case .GBP:
return NSDecimalNumber(mantissa: 126816, exponent: -5, isNegative: false)
case .EUR:
return NSDecimalNumber(integer: 1)
case .USD:
return NSDecimalNumber(mantissa: 88203, exponent: -5, isNegative: false)
}
}
}
extension Money {
func convertedToCurrency(currency: Currency) -> Money {
let amountInEUR = amount.decimalNumberByMultiplyingBy(self.currency.singleInEUR)
let convertedAmount = amountInEUR.decimalNumberByDividingBy(currency.singleInEUR)
return Money(amount: convertedAmount, currency: currency)
}
}
extension Money: CustomStringConvertible {
var description: String {
return "\(amount) \(currency)"
}
}
let fivePounds = Money(amount: 5, currency: .GBP)
let threeEuros = Money(amount: 3, currency: .EUR)
let eightDollars = Money(amount: 8, currency: .USD)
let fivePoundsInEuros = fivePounds.convertedToCurrency(.EUR)
let fivePoundsInUSD = fivePounds.convertedToCurrency(.USD)
let eightDollarsInPounds = eightDollars.convertedToCurrency(.GBP)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment