Skip to content

Instantly share code, notes, and snippets.

@Edudjr
Forked from cwagdev/Luhn.swift
Last active February 15, 2024 20:33
Show Gist options
  • Save Edudjr/1f90b75b13017b5b0aec2be57187d119 to your computer and use it in GitHub Desktop.
Save Edudjr/1f90b75b13017b5b0aec2be57187d119 to your computer and use it in GitHub Desktop.
Luhn Algorithm in Swift 4.1
func luhnCheck(_ number: String) -> Bool {
var sum = 0
let digitStrings = number.reversed().map { String($0) }
for tuple in digitStrings.enumerated() {
if let digit = Int(tuple.element) {
let odd = tuple.offset % 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
}
//testing
//VISA
print(luhnCheck("4929939187355598")) //true
print(luhnCheck("4485383550284604")) //true
print(luhnCheck("4532307841419094")) //true
print(luhnCheck("4716014929481859")) //true
print(luhnCheck("4539677496449015")) //true
print(luhnCheck("4129939187355598")) //false
print(luhnCheck("4485383550184604")) //false
print(luhnCheck("4532307741419094")) //false
print(luhnCheck("4716014929401859")) //false
print(luhnCheck("4539672496449015")) //false
//Master
print(luhnCheck("5454422955385717")) //true
print(luhnCheck("5582087594680466")) //true
print(luhnCheck("5485727655082288")) //true
print(luhnCheck("5523335560550243")) //true
print(luhnCheck("5128888281063960")) //true
print(luhnCheck("5454452295585717")) //false
print(luhnCheck("5582087594683466")) //false
print(luhnCheck("5487727655082288")) //false
print(luhnCheck("5523335500550243")) //false
print(luhnCheck("5128888221063960")) //false
//Discover
print(luhnCheck("6011574229193527")) //true
print(luhnCheck("6011908281701522")) //true
print(luhnCheck("6011638416335074")) //true
print(luhnCheck("6011454315529985")) //true
print(luhnCheck("6011123583544386")) //true
print(luhnCheck("6011574229193127")) //false
print(luhnCheck("6031908281701522")) //false
print(luhnCheck("6011638416335054")) //false
print(luhnCheck("6011454316529985")) //false
print(luhnCheck("6011123581544386")) //false
//American Express
print(luhnCheck("348570250878868")) //true
print(luhnCheck("341869994762900")) //true
print(luhnCheck("371040610543651")) //true
print(luhnCheck("341507151650399")) //true
print(luhnCheck("371673921387168")) //true
print(luhnCheck("348570250872868")) //false
print(luhnCheck("341669994762900")) //false
print(luhnCheck("371040610573651")) //false
print(luhnCheck("341557151650399")) //false
print(luhnCheck("371673901387168")) //false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment