Validate Credit Card Number — Luhn’s Check Algorithm Explained in Swift

Derek Kim
5 min readAug 21, 2023

Hello everyone, this is Derek.

It has been quite a while since I’ve written a blog due to lot of things going on in my life like preparing for job interviews and family emergency, but I am back at it now!

Today I will be writing about Luhn’s Check Algorithm, which is widely used algorithm for checking the credit card number’s validity.

Ever wondered how that small piece of plastic in your wallet knows when you mistype a single digit? The magic behind this is the Luhn’s Check Algorithm, an unsung hero in the world of finance, tirelessly working behind the scenes to ensure that credit card numbers are valid.

Luhn’s.. What Now?

In the simplest of words, the Luhn’s Check Algorithm, or Modulus 10 Algorithm, is a formula used by many industries to validate identification numbers, especially credit card numbers. If you ever typed in a wrong card number online and got an instant error without even hitting the submit button — yup, that’s Luhn’s algorithm doing its thing.

Very important facts listed in Wikipedia:

It is not intended to be a cryptographically secure hash function, but it was more designed to protect against accidental errors, not malicious attacks.

Most credit cards and many government identication numbers use the algorithm as a simple method of distinguishing valid numbers from mistyped or otherwise incorrect numbers.

So how is it computed? Let’s break it down step-by-step in simple terms.

  1. Reverse those digits: Turn that credit card number around.
  2. Sum it up: Calculate the sum of digits at even places
  3. Double the odd ones: For digits at odd places, double them.
  4. Got a two-digit number? If your doubled digit exceeds 9, either add the two digits together or simply subtract 9.
  5. Combine and check: Add up the sums from steps 2 and 3. If the total sum is a perfect multiple of 10 (or in other words, divisible by 10), we have a valid credit card number. If not, it’s invalid.

Decoding Luhn’s Algorithm with Swift

--

--