Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
マイナンバー チェックデジット
extension String {
func isValidMyNumber() -> Bool {
enum Error: ErrorType {
case NonNumber
}
let numbers: [Int]
do {
numbers = try self.characters.map { (char) -> Int in
guard let value = Int(String(char)) else {
throw Error.NonNumber
}
return value
}
} catch {
return false
}
guard numbers.count == 12 else {
return false
}
let sum = (1...11).reduce(0) { (current, index) -> Int in
let p = numbers[11 - index]
let q: Int
if 1...6 ~= index {
q = index + 1
} else {
q = index - 5
}
return current + p * q
}
return 11 - sum % 11 == numbers[11]
}
}
let matrix = [
"123456789010": false,
"123456789011": false,
"123456789012": false,
"123456789013": false,
"123456789014": false,
"123456789015": false,
"123456789016": false,
"123456789017": false,
"123456789018": true,
"123456789019": false,
"023456789013": true,
"02345678901X": false,
"02345678901XX": false,
"023456789013X": false,
]
matrix.forEach { (string, result) -> () in
assert(string.isValidMyNumber() == result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.