Skip to content

Instantly share code, notes, and snippets.

@chrsp
Last active April 7, 2019 23:25
Show Gist options
  • Save chrsp/354c1e568891188829cfef80f717228a to your computer and use it in GitHub Desktop.
Save chrsp/354c1e568891188829cfef80f717228a to your computer and use it in GitHub Desktop.
Implementação em Swift da validação de NIF português. https://pt.wikipedia.org/wiki/N%C3%BAmero_de_identifica%C3%A7%C3%A3o_fiscal
func isNifValid(nif: String) -> Bool {
guard nif.count == 9, let nifPrefix = Int(nif.prefix(1)) else { return false }
if [1, 2, 5, 6, 9].contains(nifPrefix) {
var checkDigit = nifPrefix * 9
for index in 2...nif.count - 1 {
let indexBound = nif.index(nif.startIndex, offsetBy: index - 1)
checkDigit += (Int(String(nif[indexBound])) ?? 0) * (10 - index)
}
checkDigit = 11 - (checkDigit % 11)
if checkDigit >= 10 {
checkDigit = 0
}
return checkDigit == Int(nif.suffix(1))
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment