Last active
July 2, 2019 10:23
-
-
Save jonelf/bccf58698adc12e53fd6 to your computer and use it in GitHub Desktop.
Luhn test in Swift.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.