You can define your own similarity sorting method. Note that I have also added a hasPrefix priority over the ones which only contains the keyword which you can just remove if you don't want it:
var theArray = ["chill", "nifty", "precooled", "cooldaddy", "cool", "coolguy", "dandy", "uncool"]
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) {
return false
}
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) {
return false
}
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"]
You can also extend Sequence and create a sorted by key similarity method:
extension Sequence where Element: StringProtocol {
func sorted<S>(by key: S) -> [Element] where S: StringProtocol {
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) {
return false
}
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) {
return false
}
else if $0.contains(key) && $1.contains(key)
&& $0.count < $1.count {
return true
}
return false
}
}
}
let sorted = theArray.sorted(by: key) // "cool", "coolguy", "cooldaddy", "uncool", "precooled", "chill", "nifty", "dandy"]
And the mutating version as well:
extension MutableCollection where Element: StringProtocol, Self: RandomAccessCollection {
mutating func sort<S>(by key: S) where S: StringProtocol {
sort {
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) {
return false
}
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) {
return false
}
else if $0.contains(key) && $1.contains(key)
&& $0.count < $1.count {
return true
}
return false
}
}
}