Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


parse out a number in a Specific position from an integer in SWIFT


How i can get any number from an integer in any position

example: var number = 74401

how do i get the number 4 or any number i want, ?

It depends, are you looking for the index of the number of 4, or are you looking to return any number in the thousands position? (or the hundreds position, you have two 4s)

3 Answers

Try this: It breaks a number into an array of characters, then converts the character back to an integer to sum it up. Put this into a playground:

var number = 74401
var sum = 0
var charArray = Array(String(number))

for char in charArray {

    var digit = String(char).toInt()

    sum += digit!


in fact i want to sum all the numbers

74401 => 7+4+4+0+1

so i need to get a single digit in each loop iteration

Thank u