Skip to content

Instantly share code, notes, and snippets.

@kumo
Last active April 8, 2016 17:32
Show Gist options
  • Save kumo/43781a552ee2b845da6c to your computer and use it in GitHub Desktop.
Save kumo/43781a552ee2b845da6c to your computer and use it in GitHub Desktop.
Converting to Roman Numerals using an array of tuples
func toRomanNumerals(number: Int) -> String? {
guard number > 0 else {
return nil
}
var remainder = number
let values = [("M", 1000), ("CM", 900), ("D", 500), ("CD", 400), ("C",100), ("XC", 90), ("L",50), ("XL",40), ("X",10), ("IX", 9), ("V",5),("IV",4), ("I",1)]
var result = ""
for (romanChar, arabicValue) in values {
let count = remainder / arabicValue
if count == 0 { continue }
for _ in 1...count
{
result += romanChar
remainder -= arabicValue
}
}
return result
}
toRomanNumerals(2014) // optional, otherwise toRomanTuple(2014)!
toRomanNumerals(-3) // nil
@kumo
Copy link
Author

kumo commented Aug 5, 2014

In beta 5 1...count gives an error if the range is invalid (1...0), so now I have to check for that condition

@kumo
Copy link
Author

kumo commented Apr 8, 2016

Swift 2.2 quite rightly complains about my var param, and guard is probably better than my if check.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment