鉴于以下内容:
var theArray: [String] = ["uncool", "chill", "nifty", "precooled", "dandy", "cool"]
我想通过单词与关键字的相似程度对数组进行排序。
var keyWord: String = "cool"
想要的结果将是:
print// ["cool", "uncool", "precooled", ...]
然后它就不再重要了。但are
键或contain it
应该是第一个对象。
到目前为止,我最接近的尝试是:
let _theArray = entries.sorted { element1, element2 in
return element1.contains(keyWord) && !element2.contains(keyWord)
}
但是这导致uncool
成为第一项,然后precooled
和最相关的项cool
甚至出现在nifty
之后。
我错过了什么?非常感谢帮助。
答案 0 :(得分:9)
您可以定义自己的相似性排序方法。请注意,我还添加了一个hasPrefix优先级,而不是仅包含关键字的那个,如果你不想要它,你可以删除它:
let theArray = ["uncool", "chill", "nifty", "precooled", "cooldaddy", "cool", "coolguy", "dandy"]
let key = "cool"
let sorted = theArray.sorted {
if $0 == key && $1 != key {
return true
} else if $0.hasPrefix(key) && !$1.hasPrefix(key) {
return true
} else if $0.hasPrefix(key) && $1.hasPrefix(key) && $0.count < $1.count {
return true
} else if $0.contains(key) && !$1.contains(key) {
return true
} else if $0.contains(key) && $1.contains(key) && $0.count < $1.count {
return true
}
return false
}
print(sorted) // ["cool", "coolguy", "cooldaddy", "uncool", "precooled", "chill", "nifty", "dandy"]
答案 1 :(得分:2)
首先,您需要衡量两个字符串的相似程度。这是一个简单的例子:
extension String {
func equalityScore(with string: String) -> Double {
if self == string {
return 2 // the greatest equality score this method can give
} else if self.contains(string) {
return 1 + 1 / Double(self.count - string.count) // contains our term, so the score will be between 1 and 2, depending on number of letters.
} else {
// you could of course have other criteria, like string.contains(self)
return 1 / Double(abs(self.count - string.count))
}
}
}
完成后,您可以使用它对数组进行排序:
var theArray: [String] = ["uncool", "chill", "nifty", "precooled", "dandy", "cool"]
var compareString = "cool"
theArray.sort { lhs, rhs in
return lhs.equalityScore(with: compareString) > rhs.equalityScore(with: compareString)
}
结果:["cool", "uncool", "precooled", "chill", "nifty", "dandy"]