Last active
April 7, 2019 23:25
-
-
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
This file contains 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 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