Skip to content

Instantly share code, notes, and snippets.

@micheltlutz
Last active August 12, 2020 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micheltlutz/cf3fef55059ab6c48c11df4f2e4aa6d4 to your computer and use it in GitHub Desktop.
Save micheltlutz/cf3fef55059ab6c48c11df4f2e4aa6d4 to your computer and use it in GitHub Desktop.
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