TestsTested | ✓ |
LangLanguage | SwiftSwift |
License | MIT |
ReleasedLast Release | Oct 2016 |
SPMSupports SPM | ✗ |
Maintained by Luca Serpico.
A base-independent implementation of the Luhn algorithm for Swift. Useful for generating and verifying check digits in arbitrary bases.
To consider a porting of https://github.com/benhodgson/baluhn in swift.
From Wikipedia:
The Luhn algorithm or Luhn formula, also known as the “modulus 10” or “mod 10” algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers in US and Canadian Social Insurance Numbers
Swift Package Manager coming soon.
Download the project and copy the Sources
folder content into your project to use it in.
Luhn provides two functions: verify
and generate
.
generate
calculates the Luhn check character for the given input string in the given base. This character should be appended to the input string to produce a valid Luhn string.
verify
tests whether or not a string is a valid Luhn string in the given base. By default, luhn operates in base 10:
To use it, just import Luhn in your projectimport Luhn
Clone and open the playground to see a live usage of the library.
// Genereta a value to have a valid luhn using the decimal alphabet
try Luhn.generate(baseString: "7992739871") // Generate 3
// Verify if the string is a valid luhn using the decimal alphabet
try Luhn.verify(string: "79927398713") // A valid lunh
try Luhn.verify(string: "79927398714") // An invalid luhn
// Using a defined alphabet
let alphabet = "abcdefghijklmnopqrstuvwxyz"
try Luhn.generate(baseString: "swift", alphabet: alphabet) // Returns l
try Luhn.verify(string: "swiftl", alphabet: alphabet) // A valid luhn
try Luhn.verify(string: "swiftz", alphabet: alphabet) // An invalid luhn
Special thanks to @benhodgson
Luhn is released under the MIT license. See LICENSE for details.