Last active
August 12, 2020 18:06
-
-
Save micheltlutz/cf3fef55059ab6c48c11df4f2e4aa6d4 to your computer and use it in GitHub Desktop.
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
import Foundation | |
private extension Collection where Element == Int { | |
var digitCPF: Int { | |
var number = count + 2 | |
let digit = 11 - reduce(into: 0) { | |
number -= 1 | |
$0 += $1 * number | |
} % 11 | |
return digit > 9 ? 0 : digit | |
} | |
} | |
private extension StringProtocol { | |
var isValidCPF: Bool { | |
let numbers = compactMap(\.wholeNumberValue) | |
guard numbers.count == 11 && Set(numbers).count != 1 else { return false } | |
return numbers.prefix(9).digitCPF == numbers[9] && | |
numbers.prefix(10).digitCPF == numbers[10] | |
} | |
} | |
let cpf = "11111111111".isValidCPF // false | |
let cpf = "111.111.111-11".isValidCPF // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment