Skip to content

Instantly share code, notes, and snippets.

@gservera
Last active June 10, 2019 11:33
Show Gist options
  • Save gservera/cf455332930a659ca83b to your computer and use it in GitHub Desktop.
Save gservera/cf455332930a659ca83b to your computer and use it in GitHub Desktop.
Validar DNI español o calcular su letra en Swift 2.0
import Foundation
/**
Valida el número y la(s) letra(s) de un cualquier documento nacional de identidad
español (NIF o NIE) utilizando una implementación del algoritmo oficial.
- parameter nationalID: El DNI que se validará. No distingue mayúsculas y minúsculas.
- returns: `true` si el DNI proporcionado es válido o `false` si no lo es.
*/
func validateSpanishNationalIdentifier(nationalID: String) -> Bool {
guard nationalID.characters.count == 9 else {
return false
}
let buffer = NSMutableString(string: nationalID.uppercaseString)
let opts = NSStringCompareOptions()
let rng = NSMakeRange(0, 1)
buffer.replaceOccurrencesOfString("X", withString: "0", options: opts, range: rng)
buffer.replaceOccurrencesOfString("Y", withString: "1", options: opts, range: rng)
buffer.replaceOccurrencesOfString("Z", withString: "2", options: opts, range: rng)
if let baseNumber = Int(buffer.substringToIndex(8)) {
let letterMap = "TRWAGMYFPDXBNJZSQVHLCKET"
let letterIdx = baseNumber % 23
let expectedLetter = letterMap[letterMap.startIndex.advancedBy(letterIdx)]
let providedLetter = (buffer as String)[nationalID.endIndex.predecessor()]
return (expectedLetter == providedLetter)
} else {
return false
}
}
/**
Intenta calcular la letra de cualquier documento nacional de identidad español (NIF o
NIE) a partir de sus dígitos utilizando una implementación del algoritmo oficial.
- parameter baseNumber: Los dígitos DNI del cuál quiere calcularse la letra.
- returns: La letra correspondiente si el DNI tiene el formato correcto o `nil` si el
cáclulo falla.
*/
func expectedLetterForSpanishNationalIdentifier(baseNumber: String) -> String? {
guard baseNumber.characters.count == 8 else {
return nil
}
let buffer = NSMutableString(string: baseNumber.uppercaseString)
let opts = NSStringCompareOptions()
let rng = NSMakeRange(0, 1)
buffer.replaceOccurrencesOfString("X", withString: "0", options: opts, range: rng)
buffer.replaceOccurrencesOfString("Y", withString: "1", options: opts, range: rng)
buffer.replaceOccurrencesOfString("Z", withString: "2", options: opts, range: rng)
if let baseNumber = Int(buffer as String) {
let letterMap = "TRWAGMYFPDXBNJZSQVHLCKET"
let letterIdx = baseNumber % 23
let expectedLetter = letterMap[letterMap.startIndex.advancedBy(letterIdx)]
return String(expectedLetter)
} else {
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment