Last active
January 2, 2018 23:39
-
-
Save caioremedio/a35cbb4c6097649dbe22009266867051 to your computer and use it in GitHub Desktop.
Swift CPF Validator
This file contains hidden or 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
static func isValidCPF(_ CPF: String) -> Bool { | |
// | |
// CPF must have 14 full characters, and 11 numeric values | |
// | |
if CPF.count != 14 { return false } | |
let cpfDigits = CPF.numericValues() | |
if cpfDigits.count != 11 { return false } | |
let CPFArray = cpfDigits.map({ Int(String($0)) ?? -1 }) | |
// | |
// Algorithm | |
// | |
var hasSameValues = true | |
var digito = 0 | |
for i in 0..<(CPFArray.count - 1) { | |
digito = CPFArray[i] | |
if digito > 9 || digito < 0 { return false } | |
if digito != CPFArray[i + 1] { | |
hasSameValues = false | |
break | |
} | |
} | |
if hasSameValues { return false } | |
for i in 9 ..< 11 { | |
var soma = 0 | |
var k: Int = 0 | |
for _ in 0 ..< i { | |
soma += CPFArray[k] * ((i + 1) - k) | |
k += 1 | |
} | |
soma = ((10 * soma) % 11) % 10 | |
if CPFArray[k] != soma { return false } | |
} | |
return true | |
} | |
extension String { | |
func numericValues() -> String { | |
if self.isEmpty { return self } | |
return String.matchesForRegex("[0-9]", inText: self) | |
} | |
static func matchesForRegex(_ regex: String, inText text: String) -> String { | |
do { | |
let regex = try NSRegularExpression(pattern: regex, options: []) | |
let nsString = text as NSString | |
let results = regex.matches(in: text, | |
options: [], | |
range: NSMakeRange(0, nsString.length)) | |
let mappedResults = results.map { nsString.substring(with: $0.range) } | |
return mappedResults.joined(separator: "") | |
} catch let error as NSError { | |
print("\(#function) - invalid regex: \(error.localizedDescription)") | |
return text | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment