Skip to content

Instantly share code, notes, and snippets.

@jonelf
Last active July 2, 2019 10:23
Show Gist options
  • Save jonelf/bccf58698adc12e53fd6 to your computer and use it in GitHub Desktop.
Save jonelf/bccf58698adc12e53fd6 to your computer and use it in GitHub Desktop.
Luhn test in Swift.
func lunhCheck(number : String) -> Bool
{
let reversed = reverse(number).map { String($0).toInt()! }
return reduce(enumerate(reversed), 0, {(sum, val) in
let odd = val.index % 2 == 1
return sum + (odd ? (val.element == 9 ? 9 : (val.element * 2) % 9) : val.element)
}) % 10 == 0
}
lunhCheck("49927398716")
lunhCheck("49927398717")
@cwagdev
Copy link

cwagdev commented Jul 17, 2015

This was helpful, thanks for posting. I however found the nested ternaries very difficult to read, I also didn't like the forced unwrapping. So, I came up with the following, hope this can help anyone who lands here.

func luhnCheck(number: String) -> Bool {
    var sum = 0
    let digitStrings = reverse(number).map { String($0) }

    for tuple in enumerate(digitStrings) {
        if let digit = tuple.element.toInt() {
            let odd = tuple.index % 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
}

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