-
-
Save JaDenis/f03e26f6e83888ccdae66d424d4881d7 to your computer and use it in GitHub Desktop.
Luhn Algorithm in Swift
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 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