Skip to content

Instantly share code, notes, and snippets.

@jonahaung
Last active January 30, 2024 04:47
Show Gist options
  • Save jonahaung/6afa0bcf7136fa1cc226eaaa9995ed55 to your computer and use it in GitHub Desktop.
Save jonahaung/6afa0bcf7136fa1cc226eaaa9995ed55 to your computer and use it in GitHub Desktop.
Validate Singapore NRIC
func validateSingaporeNRIC(_ nricString: String) -> Bool {
let str = nricString.uppercased()
let characters = [Character](str)
if characters[0] == "M" {
return true
}
guard str.count == 9 else { return false }
var weight = 0
weight += String(characters[1]) == " " ? 0 : (Int(String(characters[1])) ?? 0) * 2
weight += String(characters[2]) == " " ? 0 : (Int(String(characters[2])) ?? 0) * 7
weight += String(characters[3]) == " " ? 0 : (Int(String(characters[3])) ?? 0) * 6
weight += String(characters[4]) == " " ? 0 : (Int(String(characters[4])) ?? 0) * 5
weight += String(characters[5]) == " " ? 0 : (Int(String(characters[5])) ?? 0) * 4
weight += String(characters[6]) == " " ? 0 : (Int(String(characters[6])) ?? 0) * 3
weight += String(characters[7]) == " " ? 0 : (Int(String(characters[7])) ?? 0) * 2
if characters.first == "T" || characters.first == "G" {
weight += 4
}
let temp = weight % 11
let st = ["J", "Z", "I", "H", "G", "F", "E", "D", "C", "B", "A"]
let fg = ["X", "W", "U", "T", "R", "Q", "P", "N", "M", "L", "K"]
var theAlpha: String?
if characters.first == "S" || characters.first == "T" {
theAlpha = st[temp]
} else if characters.first == "F" || characters.first == "G" {
theAlpha = fg[temp]
}
if String(characters[8]) == theAlpha {
return true
}
return false
}
@jonahaung
Copy link
Author

print(validateSingaporeNRIC("S8473912z"))

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