Created
November 9, 2017 14:26
-
-
Save mmar/8a3042fb770463c5f1362bb050c71e6e to your computer and use it in GitHub Desktop.
The roman numeral representation of an Int.
This file contains hidden or 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
| extension Int { | |
| func toRoman(uppercase: Bool = true) -> String? { | |
| guard self > 0, self < 4000 else { return nil } | |
| let romanDigits = | |
| [["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"], | |
| ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"], | |
| ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"], | |
| ["", "M", "MM", "MMM"]] | |
| let romanNumber = String(self).reversed().enumerated() | |
| .map { romanDigits[$0.offset][Int(String($0.element))!] } | |
| .reversed().joined() | |
| return uppercase ? romanNumber : romanNumber.lowercased() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment