Skip to content

Instantly share code, notes, and snippets.

@kumo
Last active July 17, 2020 10:22
Show Gist options
  • Save kumo/44178f2246364ffef9bb to your computer and use it in GitHub Desktop.
Save kumo/44178f2246364ffef9bb to your computer and use it in GitHub Desktop.
Converting to Arabic numbers using tuples
import UIKit
func toArabic(romanNumerals: String) -> Int? {
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 romanNumerals = romanNumerals
var result = 0
for (romanChars, arabicValue) in values {
let range = romanChars.startIndex ..< romanChars.endIndex
while romanNumerals.hasPrefix(romanChars) {
result = result + arabicValue
romanNumerals.removeSubrange(range)
}
}
guard (romanNumerals.isEmpty) else {
return nil
}
return result
}
toArabic(romanNumerals: "MCM") // Some 1,900
toArabic(romanNumerals: "MCMZ") // nil
toArabic(romanNumerals: "ROB") // nil
@evision1
Copy link

evision1 commented Feb 6, 2015

I am getting an error on line: romanNumerals = romanNumerals.substringFromIndex(size)
'Int' is not convertible to 'String.Index'

@evision1
Copy link

evision1 commented Feb 6, 2015

Got it!
Change line: romanNumerals = romanNumerals.substringFromIndex(size)
To this: romanNumerals = (romanNumerals as NSString).substringFromIndex(size)

@charoitel
Copy link

Got following errors and made following changes to fix it:

  • Use of unresolved identifier 'count'

Change line: let size = count(romanChar)
To this: let size = romanChar.count

  • 'substringFromIndex' has been renamed to 'substring(from:)'

Change line: romanNumerals = (romanNumerals as NSString).substringFromIndex(size)
To this: romanNumerals = (romanNumerals as NSString).substring(from: size)

@kumo
Copy link
Author

kumo commented Nov 27, 2019

Thanks for the feedback and corrections.

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