Last active
October 11, 2015 16:24
-
-
Save SimplGy/7a93b8972ac00fbccdb0 to your computer and use it in GitHub Desktop.
Playing around with enums and computed properties as a way to display formatted values in Swift. Usage: `let sek = Currency.Code(rawValue: "SEK"); print(sek.display("42.50")`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Currency { | |
static private let decimals: [Code: Int] = [ | |
Code.None: 0, | |
Code.DKK: 2, | |
Code.GBP: 2, | |
Code.NOK: 2, | |
Code.SEK: 2, | |
Code.USD: 2, | |
Code.XBT: 2 | |
] | |
static private let formatStrings: [Code: String] = [ | |
Code.None: "%@ Rupees", | |
Code.DKK: "%@ DKK", | |
Code.GBP: "%@ GBP", | |
Code.NOK: "%@ NOK", | |
Code.SEK: "%@ SEK", | |
Code.USD: "$%@", | |
Code.XBT: "%@ XBT" | |
] | |
static private var formatters: [Code: NSNumberFormatter] = [ | |
Code.None: NSNumberFormatter() | |
] | |
static private func makeFormatter(code: Code) -> NSNumberFormatter { | |
let d = decimals[code]! | |
// ensure decimals max length | |
let nf = NSNumberFormatter() | |
nf.numberStyle = NSNumberFormatterStyle.DecimalStyle | |
nf.minimumFractionDigits = 0 // strip trailing zeros | |
nf.maximumFractionDigits = d | |
return nf | |
} | |
enum Code: String, CustomStringConvertible { | |
case None = "_" | |
case DKK = "DKK" // Danish krone | |
case GBP = "GBP" // Pound sterling | |
case NOK = "NOK" // Norwegian krone | |
case SEK = "SEK" // Swedish krona/kronor | |
case USD = "USD" // United States dollar | |
case XBT = "XBT" // Bitcoin | |
var description: String { return self.rawValue } | |
var formatString: String { return formatStrings[self]! } | |
// Manually implement a lazy getter, since enums can't store properties | |
var formatter: NSNumberFormatter { | |
if let nf = formatters[self] { | |
return nf | |
} else { | |
let nf = NSNumberFormatter() | |
formatters[self] = nf | |
return nf | |
} | |
} | |
func display(amount: NSDecimalNumber) -> String { | |
let strAmount = self.formatter.stringFromNumber(amount) | |
return String(format: self.formatString, strAmount) | |
} | |
} | |
func tryIt() { | |
let sekCurrency = Code(rawValue: "SEK")! | |
print(sekCurrency.display("42.50")) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment