Skip to content

Instantly share code, notes, and snippets.

@JaDenis
Forked from cwagdev/Luhn.swift
Created September 1, 2016 14:55
Show Gist options
  • Save JaDenis/f03e26f6e83888ccdae66d424d4881d7 to your computer and use it in GitHub Desktop.
Save JaDenis/f03e26f6e83888ccdae66d424d4881d7 to your computer and use it in GitHub Desktop.
Luhn Algorithm in Swift
func luhnCheck(number: String) -> Bool {
var sum = 0
let digitStrings = reverse(number).map { String($0) }
for tuple in enumerate(digitStrings) {
if let digit = tuple.element.toInt() {
let odd = tuple.index % 2 == 1
switch (odd, digit) {
case (true, 9):
sum += 9
case (true, 0...8):
sum += (digit * 2) % 9
default:
sum += digit
}
} else {
return false
}
}
return sum % 10 == 0
}
luhnCheck("49927398716")
luhnCheck("49927398717")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment