Skip to content

Instantly share code, notes, and snippets.

@J-L
Last active January 31, 2017 16:46
Show Gist options
  • Save J-L/e2294d19677bbb34c6e1 to your computer and use it in GitHub Desktop.
Save J-L/e2294d19677bbb34c6e1 to your computer and use it in GitHub Desktop.
Swift Implementation of Luhn Algorithm
//: Playground - noun: a place where people can play
/*
From wikipedia:
From the rightmost digit, which is the check digit, moving left, double the value of every second digit; if the product of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then sum the digits of the products (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9).
Take the sum of all the digits.
If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.
*/
import UIKit
func luhnAlgorithm(cardNumber: String) -> Bool{
var luhn_sum = 0
var digit_count = 0
//reverse the card
for c in cardNumber.characters.reverse() {
//count digits
print(c.self)
let this_digit = Int(String(c as Character))!
print(this_digit)
digit_count++
//double every even digit
if digit_count % 2 == 0{
if this_digit * 2 > 9 {
luhn_sum = luhn_sum + this_digit * 2 - 9
}else{
luhn_sum = luhn_sum + this_digit * 2
}
}else{
luhn_sum = luhn_sum + this_digit
}
}
if luhn_sum % 10 == 0{
return true
}
return false
}
luhnAlgorithm("6011497870742170")
@ampilogov
Copy link

let this_digit = Int(String(c as Character))! - it might be crash

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment