Skip to content

Instantly share code, notes, and snippets.

@LucianoPAlmeida
Last active August 4, 2018 01:47
Show Gist options
  • Save LucianoPAlmeida/6c9f041ff4f38a156218596c07830b32 to your computer and use it in GitHub Desktop.
Save LucianoPAlmeida/6c9f041ff4f38a156218596c07830b32 to your computer and use it in GitHub Desktop.
CPF Validator in swift
struct CPFValidator {
var cpf: String
// Based on:
// https://pt.stackoverflow.com/questions/187106/valida%C3%A7%C3%A3o-cpf-e-cnpj
func validate() -> Bool {
let numbers = cpf.compactMap { (char) -> Int? in
return Int(char)
}
guard numbers.count == 11 && Set(numbers).count != 1 else { return false }
let sum1 = self.sum(slice: numbers[0..<9], initialValue: 10)
let dv1 = sum1 > 9 ? 0 : sum1
let sum2 = self.sum(slice: numbers[0..<10], initialValue: 11)
let dv2 = sum2 > 9 ? 0 : sum2
return dv1 == numbers[9] && dv2 == numbers[10]
}
private func sum(slice: ArraySlice<Int>, initialValue: Int) -> Int {
let enumSlice: EnumeratedSequence<ArraySlice<Int>> = slice.enumerated()
let reduced = enumSlice.reduce(into: 0, { (acc, value) in
acc+=(value.element * (initialValue-value.offset))
})
return 11 - (reduced % 11)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment