roman numeral to int in swift

Here's an extension in Swift that converts a Roman numeral string to an Int value:

main.swift
extension String {
    func romanNumeralToInt() -> Int {
        let romanDict = ["I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000]
        var result = 0
        
        for i in 0..<count {
            let current = romanDict[String(self[index(startIndex, offsetBy: i)])] ?? 0
            let next = (i+1 < count) ? romanDict[String(self[index(startIndex, offsetBy: i+1)])] ?? 0 : 0
            
            if current < next {
                result -= current
            } else {
                result += current
            }
        }
        
        return result
    }
}
598 chars
20 lines

This function uses a dictionary to map each Roman numeral character to an integer value. It then iterates through the string, comparing adjacent characters to determine whether to add or subtract from the result, based on whether the current character is smaller or larger than the next character.

Here's an example usage of the extension:

main.swift
let romanNumeral = "MCMXCIV"
let integerValue = romanNumeral.romanNumeralToInt() // 1994
89 chars
3 lines

gistlibby LogSnag