Search code examples
swiftswift-playgroundswift-array

Why does ("0"+"1").toInt()! return 1 as an Int, rather than 0


Was playing around with the reduce function on collections in Swift.

//Reduce method should return an Int with the value 3141.
let digits = ["3", "1", "4", "1"]
.reduce(0) {
    (total:Int, digit:String) in
    return ("\(total)" + digit).toInt()!
}

The function is giving the correct output but why does ("0"+"1").toInt()! return 1 as an Int, rather than 0? The string combined to be turned into an Int is "01". I assume this is a String that the function cannot covert to an Int directly. Does it just default to the second character instead?


Solution

  • "0"+"1" == "01". You're doing concatenation not addition. You lose the 0 when you convert to int because it's a leading zero.

    Leading zero's are usually dropped as meaningless but in some contexts they actually signal that you're expressing an octal based number. Even if that's the case here it'd still end up evaluating to 1.