Skip to content

Instantly share code, notes, and snippets.

@Rashidium
Last active February 8, 2017 12:05
Show Gist options
  • Save Rashidium/b69a103779166c7e8acda07fbaba656f to your computer and use it in GitHub Desktop.
Save Rashidium/b69a103779166c7e8acda07fbaba656f to your computer and use it in GitHub Desktop.
Vehicle Identification Number (VIN or chassis number) validation in Swift 3.0 with String extension
//
// Created by Rashid Ramazanov on 18/01/2017.
// Converted from Java snippet in https://en.wikipedia.org/wiki/Vehicle_identification_number#Example_Code
//
import Foundation
extension String {
var isValidChassisNo: Bool {
return getCheckDigit(vin: self) == (self as NSString).character(at: 8)
}
private func transliterate(char: unichar) -> Int {
return ("0123456789.ABCDEFGH..JKLMN.P.R..STUVWXYZ" as NSString).range(of: String(Character(UnicodeScalar(char)!))).location % 10
}
private func getCheckDigit(vin: String) -> unichar {
let map: NSString = "0123456789X"
let weights: NSString = "8765432X098765432"
var sum = 0
for (index, _) in vin.characters.enumerated() {
sum += transliterate(char: (vin as NSString).character(at: index)) * map.range(of: String(Character(UnicodeScalar(weights.character(at: index))!))).location
}
return map.character(at: sum % 11)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment