Created
July 6, 2014 10:42
-
-
Save advantis/b96adefb75cc2a0c685a to your computer and use it in GitHub Desktop.
Hybrid Luhn algorithm
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 isLuhnValid(number: String) -> Bool { | |
let asciiOffset: UInt8 = 48 | |
let digits = Array(number.utf8).reverse().map{$0 - asciiOffset} | |
let convert: (UInt8) -> (UInt8) = { | |
let n = $0 * 2 | |
return n > 9 ? n - 9 : n | |
} | |
var sum: UInt8 = 0 | |
for (index, digit) in enumerate(digits) { | |
if index & 1 == 1 { | |
sum += convert(digit) | |
} else { | |
sum += digit | |
} | |
} | |
return sum % 10 == 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment