Skip to content

Instantly share code, notes, and snippets.

@MojtabaHs
Created December 15, 2020 15:14
Show Gist options
  • Save MojtabaHs/a265047a01a957c6787135ac37d2d6cc to your computer and use it in GitHub Desktop.
Save MojtabaHs/a265047a01a957c6787135ac37d2d6cc to your computer and use it in GitHub Desktop.
The logic to validate Iranian National Code
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