swiftswift3levenshtein-distancerosetta-code

Levenshtein distance in Swift3


I'm using a tutorial from Rosetta Code to calculate Levenshtein distance. It seems their code is in Swift2 so I get this error Binary operator '+' cannot be applied to operands of type '[Int]' and 'Repeated<String.CharacterView>' when doing this: var cur = [i + 2] + empty where let empty = repeatElement(s, count: 0). How can I go about this?


Solution

  • There were a couple of changes to make.

    So the function is now

    Swift 4:

    func levDis(_ w1: String, _ w2: String) -> Int {
        let empty = [Int](repeating:0, count: w2.count)
        var last = [Int](0...w2.count)
    
        for (i, char1) in w1.enumerated() {
            var cur = [i + 1] + empty
            for (j, char2) in w2.enumerated() {
                cur[j + 1] = char1 == char2 ? last[j] : min(last[j], last[j + 1], cur[j]) + 1
            }
            last = cur
        }
        return last.last!
    }
    

    Swift 3:

    func levDis(w1: String, w2: String) -> Int {
    
        let (t, s) = (w1.characters, w2.characters)
    
        let empty = Array<Int>(repeating:0, count: s.count)
        var last = [Int](0...s.count)
    
        for (i, tLett) in t.enumerated() {
            var cur = [i + 1] + empty
            for (j, sLett) in s.enumerated() {
                cur[j + 1] = tLett == sLett ? last[j] : min(last[j], last[j + 1], cur[j])+1
            }
            last = cur
        }
        return last.last!
    }