Skip to content

Instantly share code, notes, and snippets.

@lorismaz
Created April 26, 2017 00:23
Show Gist options
  • Save lorismaz/ad05f5031a228be0b219cbdd7914ce3a to your computer and use it in GitHub Desktop.
Save lorismaz/ad05f5031a228be0b219cbdd7914ce3a to your computer and use it in GitHub Desktop.
ABA Routing Number Validation in Swift3. Inspired by http://www.brainjar.com/js/validation/ and ported to Swift 3
let routingNumber = "026009593"
func isRoutingValid(routingNumber: String) -> Bool {
let t = String(routingNumber.characters.filter { "1234567890".characters.contains($0) })
let count = t.characters.count
guard count == 9 else { return false }
var n = 0
// Run through each digit and calculate the total.
for i in stride(from: 0, to: count, by: 3) {
guard let a = Int(String(t[t.index(t.startIndex, offsetBy: i)])),
let b = Int(String(t[t.index(t.startIndex, offsetBy: i+1)])),
let c = Int(String(t[t.index(t.startIndex, offsetBy: i+2)])) else { return false }
n += (a * 3) + (b * 7) + c
}
//print(n)
// If the resulting sum is an even multiple of ten (but not zero),
// the aba routing number is good.
return n != 0 && n%10 == 0
}
isRoutingValid(routingNumber: routingNumber)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment