Created
June 7, 2016 14:08
-
-
Save LeonardoCardoso/3517ff69e4a45012fa6c8d9cbb506730 to your computer and use it in GitHub Desktop.
Validar CPF em Swift
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
extension String { | |
var isCPF: Bool { | |
let cpf = self.stringByReplacingOccurrencesOfString(".", withString: "").stringByReplacingOccurrencesOfString("-", withString: "") | |
if cpf.characters.count == 11 { | |
let d1 = Int(cpf.substringWithRange(Range(cpf.startIndex.advancedBy(9) ..< cpf.startIndex.advancedBy(10)))) | |
let d2 = Int(cpf.substringWithRange(Range(cpf.startIndex.advancedBy(10) ..< cpf.startIndex.advancedBy(11)))) | |
var temp1 = 0, temp2 = 0 | |
for i in 0...8 { | |
let char = Int(cpf.substringWithRange(Range(cpf.startIndex.advancedBy(i) ..< cpf.startIndex.advancedBy(i + 1)))) | |
temp1 += char! * (10 - i) | |
temp2 += char! * (11 - i) | |
} | |
temp1 %= 11 | |
temp1 = temp1 < 2 ? 0 : 11-temp1 | |
temp2 += temp1 * 2 | |
temp2 %= 11 | |
temp2 = temp2 < 2 ? 0 : 11-temp2 | |
if temp1 == d1 && temp2 == d2 { | |
return true | |
} | |
} | |
return false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
um de CNPJ seria muito diferente disso?