Search code examples
swift3typecasting-operator

Working with digits in numbers in Swift 3


Say you have a number...

var number = 643

and you want to do some math on it.

For example, you'd want to take the last two digits (43) and see if an integer leaves no remainder for the the last two digits minus the last digit.

For example:

var remainder = 40 % 5  //'5' is the random integer, and 40 is the last two digits(43) minus the last digit(3)

This would be rather trivial in vbscript but somehow being a newbie in Swift 3 I cannot get this done in the playground.

If I do

var number = 643
var str = (String)number
let lastChar = str.characters.last
var digit = 0
digit = Int(lastChar)

The last line gives out a warning Cannot invoke initializer for type 'Int' with an argument list of type '(String.CharacterView._Element?)'

enter image description here

Could someone please help me out? I was not able to find the answer using google in more than 30 minutes and normally I'm good in shorter time...

Thank you kindly


Solution

  • I think this is easier to do with just integer manipulation:

    let number = 643
    
    let last2Digits = number % 100 // 43
    let lastDigit = number % 10 // 3
    
    let result = last2Digits - lastDigit //40