Skip to content

Instantly share code, notes, and snippets.

@kumo
Last active June 16, 2016 08:02
Show Gist options
  • Save kumo/472043819fec7a3737f8 to your computer and use it in GitHub Desktop.
Save kumo/472043819fec7a3737f8 to your computer and use it in GitHub Desktop.
Roman Nums in Swift
//: Playground - noun: a place where people can play
import UIKit
extension Int {
func toRoman() -> String? {
var number = self
guard number > 0 else {
return nil
}
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 = number / arabicValue
if count == 0 { continue }
for _ in 1...count
{
result += romanChar
number -= arabicValue
}
}
return result
}
}
13.toRoman()
(12+15).toRoman()
2015.toRoman()
0.toRoman()
extension String {
func toArabic() -> Int? {
var string = self as String
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 = 0
for (romanChars, arabicValue) in values {
let range = romanChars.startIndex ..< romanChars.endIndex
while string.hasPrefix(romanChars) {
result = result + arabicValue
#if swift(>=3.0)
string.removeSubrange(range)
#else
string.removeRange(range)
#endif
}
}
if (string.isEmpty) {
return result
}
return nil
}
}
"MCMXXV".toArabic()
"XIII".toArabic()
"R0B".toArabic()
@kumo
Copy link
Author

kumo commented Jun 29, 2015

Pretty much the same as the previous Swift versions, but this time I preferred to use removeRange rather than substringFromIndex

@ken0nek
Copy link

ken0nek commented Dec 4, 2015

@kumo like this?

for (romanChars, arabicValue) in values {
    while string.hasPrefix(romanChars) {
        result = result + arabicValue        
        string = string.substringFromIndex(romanChars.endIndex)
    }
}

@kumo
Copy link
Author

kumo commented Apr 8, 2016

Using ..< for the range

@kumo
Copy link
Author

kumo commented Jun 16, 2016

Adding support for Swift 3 (removeSubrange instead of removeRange)

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