Skip to content

Instantly share code, notes, and snippets.

@mulatinho
Last active February 17, 2017 02:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mulatinho/14546ff8f24eb5b10e01 to your computer and use it in GitHub Desktop.
Save mulatinho/14546ff8f24eb5b10e01 to your computer and use it in GitHub Desktop.
Validação de CPF no Swift
// algoritmo: res1 = sum(digits[0-9] * 10...2) % 11; res2 = sum(digits[0-10] * 11...2) % 11
// if (digit10 == res1 && digit11 && res2) { cpf valido }
func checkIfCPFisValid(obj: AnyObject?) -> Bool
{
var input: String = ""
if let object = obj as? UITextField {
input = object.text!
}
if (input.isEmpty) {
return false
}
let cpf = input.characters.filter{"0123456789".characters.contains($0)}
if cpf.count == 11 {
let digitTen = (Int(String(cpf[9])) ?? 0)
let digitEleven = (Int(String(cpf[10])) ?? 0)
var resultModuleOne: Int = 0, resultModuleTwo: Int = 0, realValue: Int = 0
var i: Int = 0, j: Int = 11
for index in 0..<cpf.count-1 {
realValue = (Int(String(cpf[index])) ?? 0)
resultModuleTwo += (realValue * j)
if (i > 0) {
realValue = (Int(String(cpf[index-1])) ?? 0)
resultModuleOne += (realValue * j)
}
i++; j--;
}
resultModuleOne %= 11
resultModuleOne = resultModuleOne < 2 ? 0 : resultModuleOne-11
resultModuleTwo %= 11
resultModuleTwo = resultModuleTwo < 2 ? 0 : resultModuleTwo-11
if (resultModuleOne == digitTen && resultModuleTwo == digitEleven) {
return true
}
}
return false
}
let cpf: String = "fdasfdfsdf352353"
let ret: Bool
ret = checkIfCPFisValid(cpf)
print ("\n\nret is '\(ret)' and cpf if '\(cpf)'")
if (!ret) {
print ("CPF é inválido")
} else {
print ("CPF é válido!! :-)")
}
@gonzula
Copy link

gonzula commented May 27, 2016

Actually this don't work…

@mulatinho
Copy link
Author

mulatinho commented Jul 7, 2016

@ceafdc It works fine, running in production here :) I will change to my last version for my blog,
you can read here and see this working if you like: https://alex.mulatinho.net/2016/03/15/validate-fields-and-other-objects-in-swift-ios/

@mauriciorbernardo
Copy link

mauriciorbernardo commented Feb 17, 2017

Thanks for the sharing this, you need to do a little adjustment:

    resultModuleOne %= 11
    resultModuleOne = resultModuleOne < 2 ? 0 :11-resultModuleOne
    
    resultModuleTwo %= 11
    resultModuleTwo = resultModuleTwo < 2 ? 0 : 11-resultModuleTwo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment