我使用Rosetta Code的教程来计算Levenshtein距离。看起来他们的代码在Swift2中,因此我在执行此操作时遇到此错误import 'nativescript-localstorage';
:Binary operator '+' cannot be applied to operands of type '[Int]' and 'Repeated<String.CharacterView>'
其中var cur = [i + 2] + empty
。我怎么能这样做呢?
答案 0 :(得分:5)
要做出一些改变。
所以函数现在是
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!
}
斯威夫特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!
}
答案 1 :(得分:1)
由于@Daniel Illescas 的回答不起作用,这里是带有 Duck.prototype
返回类型和断言的工作版本。
Int
答案 2 :(得分:0)
func ~=(string: String, otherString: String) -> Bool {
return string.levenshteinDistanceScore(to: otherString) >= 0.85
}