How to get the Nth digit of a number in Swift

1 Answer

0 votes
import Foundation

/// Returns the N-th digit of a number counting from the left.
func getNthDigitFromLeft(from number: Int, position: Int) throws -> Int {

    let digitString = String(abs(number))

    guard position > 0 &&
          position <= digitString.count else {
        throw NSError(
            domain: "DigitError",
            code: 2,
            userInfo: [NSLocalizedDescriptionKey:
                "Position is out of range."]
        )
    }

    let digitCharacter = digitString[
        digitString.index(
            digitString.startIndex,
            offsetBy: position - 1
        )
    ]

    return Int(String(digitCharacter))!
}

// Example
let digit = try getNthDigitFromLeft(
    from: 12845,
    position: 3
)

print(digit) 



/*
run:

8

*/

 



answered Oct 14 by avibootz
...