Created
December 15, 2020 15:14
-
-
Save MojtabaHs/a265047a01a957c6787135ac37d2d6cc to your computer and use it in GitHub Desktop.
The logic to validate Iranian National Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func validateNationalCode(_ code: String) -> Bool { | |
let stringCode = code.trimmingCharacters(in: CharacterSet.decimalDigits.inverted) | |
if code.allSatisfy({ $0 == code.first }) { return false } | |
guard stringCode.count == 10 else { return false } | |
var convertedCode = code.compactMap { Int(String($0)) } | |
guard convertedCode.count == 10 else { return false } | |
let lastDigit = convertedCode.removeLast() | |
let prefixSum = convertedCode.enumerated().reduce(0) { $0 + ($1.element * (code.count - $1.offset)) } | |
let checksum = prefixSum - (prefixSum / 11) * 11 | |
if [0, 1].contains(lastDigit) && lastDigit == checksum { return true } | |
if checksum > 1 && lastDigit == abs(checksum - 11) { return true } | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment