This is a port of the Luhn Algorithm, generally used for validating debit/credit card details, written in Swift.
SwiftLuhn's HEAD is written in Swift 3. If your project doesn't support Swift 3 yet, please use the 0.1.1 tag.
Objective-C port can be found at https://github.com/MaxKramer/ObjectiveLuhn.
To run the example project, clone the repo, and run pod install
from the Example directory first.
SwiftLuhn is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod "SwiftLuhn"
Call the class method which will throws an exception SwiftLuhn.CardError
if the card is invalid.
let cardNumber = "378282246310005"
do {
try SwiftLuhn.performLuhnAlgorithm(with: cardNumber)
// process payment
}
catch {
// invalid, alert user
}
Alternatively, you can use the String
category:
let isValid = cardNumber.isValidCardNumber()
You can also get the type of the card being used which will be one of:
Card Type |
---|
American Express |
Visa |
Mastercard |
Discover |
Diner's Club |
JCB |
do {
let cardType = try SwiftLuhn.cardType(of: cardNumber)
}
catch {
// card is invalid
}
Name | Website | Reason |
---|---|---|
Paypal | http://www.paypalobjects.com/en_US/vhelp/paypalmanager_help/credit_card_numbers.htm | List of valid credit card numbers for the unit tests |
Max Kramer, [email protected], @maxkramer
SwiftLuhn is available under the MIT license. See the LICENSE file for more info.