Neil Ang

Developer

A stunning likeness of Neil Ang
Hello world

Soundex algorithm implemented in Swift

Posted on

Just for fun I thought I would try implementing the Soundex algorithm in Swift. My solution doesn't incorporate the single number for 'h' and 'w' seperated letters rule, but still generally returns the right answer.

import Foundation

class Soundex {
    class func key(word: String) -> String {
        let trimmedWord = word.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
        let letterArray = Array(trimmedWord.uppercaseString)

        if (letterArray.count < 1) {
            return ""
        }

        var soundex:[Character] = Array()

        var lastCode: Character?
        for (index, letter) in enumerate(letterArray) {
            if (soundex.count >= 3) { break }

            var code: Character

            switch letter {
            case "R":
                code = "6"
            case "M", "N":
                code = "5"
            case "L":
                code = "4"
            case "T", "D":
                code = "3"
            case "C", "S", "K", "G", "J", "Q", "X", "Z":
                code = "2"
            case "B", "P", "F", "V":
                code = "1"
            default:
                code = "0"
            }

            if (index == 0) {
                lastCode = code
                continue
            }

            if (code != "0" && code != lastCode) {
                soundex.append(code)
                lastCode = code
            }
        }

        while (soundex.count < 3) {
            soundex.append("0")
        }

        soundex.insert(letterArray.first!, atIndex: 0)

        return soundex.reduce("") { $0 + String($1) }
    }

    class func word(word: String, soundsLike: String) -> Bool {
        return self.key(word) == self.key(soundsLike)
    }
}

Here is an example of how to use this code:

println("Smith = " + Soundex.key("Smith")) // Smith = S530
println("Smyth = " + Soundex.key("Smyth")) // Smyth = S530

println("Robert = " + Soundex.key("Robert")) // Robert = R163
println("Rupert = " + Soundex.key("Rupert")) // Rupert = R163

if (Soundex.word("Smith", soundsLike: "Smyth")) {
    println("Smith and Smythe sound similar!")
}