Skip to content

Instantly share code, notes, and snippets.

@micheltlutz
Last active August 12, 2020 18:06
Show Gist options
  • Select an option

  • Save micheltlutz/cf3fef55059ab6c48c11df4f2e4aa6d4 to your computer and use it in GitHub Desktop.

Select an option

Save micheltlutz/cf3fef55059ab6c48c11df4f2e4aa6d4 to your computer and use it in GitHub Desktop.

Revisions

  1. micheltlutz revised this gist Aug 12, 2020. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion CPFValidator.swift
    Original file line number Diff line number Diff line change
    @@ -20,4 +20,5 @@ private extension StringProtocol {
    }
    }

    let cpf = "11111111111".isValidCPF // false
    let cpf = "11111111111".isValidCPF // false
    let cpf = "111.111.111-11".isValidCPF // false
  2. micheltlutz revised this gist Aug 12, 2020. 1 changed file with 3 additions and 1 deletion.
    4 changes: 3 additions & 1 deletion CPFValidator.swift
    Original file line number Diff line number Diff line change
    @@ -18,4 +18,6 @@ private extension StringProtocol {
    return numbers.prefix(9).digitCPF == numbers[9] &&
    numbers.prefix(10).digitCPF == numbers[10]
    }
    }
    }

    let cpf = "11111111111".isValidCPF // false
  3. micheltlutz created this gist Aug 12, 2020.
    21 changes: 21 additions & 0 deletions CPFValidator.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    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]
    }
    }