You yourself said "Just a simple thing like...", so I thought you were looking for a simple solution. Your complaints are no different if you were using strtol/atoi, so what's unique about swift here? Are you expecting "value of character" to be in some range that's not within 0..I have also written commercial code that does this, and I'm just going to paste it here because it's actually not that much code. Sums two strings of arbitrary length, well outside of the overflow limit, for the given base. Returns the sum as string in the base given. No mapping or overflow checks needed. Invalid characters for the base are treated as 0, but you can easily modify it to throw an error or whatever.
func sumStrings(_ left: String, _ right: String, _ radix: Int) -> String {
var left = Array(left)
var right = Array(right)
var carry = 0
var result: String = ""
while left.isEmpty == false || right.isEmpty == false {
let charLeft = left.popLast() ?? "0"
let charRight = right.popLast() ?? "0"
let intLeft = Int("\(charLeft)", radix: radix) ?? 0
let intRight = Int("\(charRight)", radix: radix) ?? 0
carry += (intLeft + intRight)
result = String(carry % radix, radix: radix, uppercase: false) + result
carry /= radix
}
if carry % radix != 0 {
result = String(carry % radix, radix: radix, uppercase: false) + result
}
return result
}