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
*/