Created
May 10, 2019 13:43
-
-
Save Marcocanc/7ea35c7c840d802baff7d5b6d5855abf to your computer and use it in GitHub Desktop.
German TIN validation
This file contains 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
func isGermanTin(tin: String) -> Bool { | |
let endIndex = tin.index(tin.startIndex, offsetBy: 10) | |
let tinNumbers = tin[..<endIndex].compactMap { Int(String($0)) } | |
// First number can't be 0 | |
guard tinNumbers.first != 0 else { return false } | |
// There should be exactly 8 or 9 unique numbers and exactly one that has 2 occurrances | |
let occurances = tinNumbers.reduce(into: [:]) { $0[$1, default: 0] += 1 } | |
guard 8...9 ~= occurances.keys.count else { return false } | |
let occurranceCount = occurances.keys.count == 9 ? 2 : 3 | |
guard occurances.values.contains(where: { $0 == occurranceCount }) else { return false } | |
// Checksum should match the 11th character | |
var sum = 0 | |
var product = 10 | |
for num in tinNumbers { | |
sum = (num + product) % 10 | |
if sum == 0 { sum = 10 } | |
product = (sum * 2) % 11 | |
} | |
var check = 11 - product | |
if check == 10 { check = 0 } | |
guard let originalCheckNum = Int(String(tin[endIndex])) else { return false } | |
return check == originalCheckNum | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment