Add / subtract characters as Int in Swift

Viewed 3574

I need to implement an algorithm to check if an input is valid by calculating a modulo of a String.

The code in Kotlin:

private val facteurs = arrayOf(7, 3, 1)

private fun modulo(s: String): Int {
    var result = 0
    var i = -1
    var idx = 0
    for (c in s.toUpperCase()) {
        val value:Int
        if (c == '<') {
            value = 0
        } else if (c in "0123456789") {
            value = c - '0'
        } else if (c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ") {
            value = c.toInt() - 55
        } else {
            throw IllegalArgumentException("Unexpected character: $c at position $idx")
        }
        i += 1
        result += value * facteurs[i % 3]
        idx += 1
    }
    return result % 10
}

This implies doing math operations on the characters.

Is there an elegant way to do this in Swift 3 and 4?

I tried some cumbersome constructs like this :

value = Int(c.unicodeScalars) - Int("0".first!.unicodeScalars)

But it does not even compile. I'm currently using Swift 4 with XCode9, but Swift3 answer is welcome too.

2 Answers
Related