Skip to content

Instantly share code, notes, and snippets.

@advantis
Created July 6, 2014 10:42
Show Gist options
  • Save advantis/b96adefb75cc2a0c685a to your computer and use it in GitHub Desktop.
Save advantis/b96adefb75cc2a0c685a to your computer and use it in GitHub Desktop.
Hybrid Luhn algorithm
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