Last active
July 17, 2020 10:22
-
-
Save kumo/44178f2246364ffef9bb to your computer and use it in GitHub Desktop.
Converting to Arabic numbers using tuples
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
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 |
Got it!
Change line: romanNumerals = romanNumerals.substringFromIndex(size)
To this: romanNumerals = (romanNumerals as NSString).substringFromIndex(size)
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)
Thanks for the feedback and corrections.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am getting an error on line: romanNumerals = romanNumerals.substringFromIndex(size)
'Int' is not convertible to 'String.Index'