Search code examples
iosswiftiban

IBAN Validator Swift


I am writing an algorithm to validate IBAN (International Bank Account Number) in Swift 3 and not able to figure one of the validation.

Example IBAN - BE68539007547034

Here are the rules to validate -

  1. Input number should be of length 16.
  2. First 2 characters are country code (not numeric).
  3. Last 14 are numeric.
  4. Last 2 characters are the modulo 97 result of the previous 12 numeric characters.

While #1 - #3 are clear I need clarity on #4. If anyone have done this before and know about it then please let me know.


Solution

  • From Wikipedia

    let IBAN = "GB82WEST12345698765432" // uppercase, no whitespace !!!!
    var a = IBAN.utf8.map{ $0 }
    while a.count < 4 {
        a.append(0)
    }
    let b = a[4..<a.count] + a[0..<4]
    let c = b.reduce(0) { (r, u) -> Int in
        let i = Int(u)
        return i > 64 ? (100 * r + i - 55) % 97: (10 * r + i - 48) % 97
    }
    print( "IBAN \(IBAN) is", c == 1 ? "valid": "invalid")
    

    prints

    IBAN GB82WEST12345698765432 is valid
    

    With IBAN from your question it prints

    IBAN BE68539007547034 is valid