我已经在iOS的Swift中成功实现了排序算法。 (请参见下面的代码)。
现在,我想在Dart for Flutter中实现相同的算法。
我必须意识到我的试用版(见下文)与Swift代码的功能不同。为什么????
有人能解释Swift的sorted
函数和Dart的sort
函数之间的区别吗?为什么我的下面的代码片段在Swift和Dart中做的不一样?
这是Swift代码:
return stationItems.sorted {
let nameA = $0.name!
.replacingOccurrences(of: ",", with: "", options: .literal, range: nil)
.replacingOccurrences(of: "ä", with: "a", options: .literal, range: nil)
.replacingOccurrences(of: "ö", with: "o", options: .literal, range: nil)
.replacingOccurrences(of: "ü", with: "u", options: .literal, range: nil)
.lowercased()
let nameB = $1.name!
.replacingOccurrences(of: ",", with: "", options: .literal, range: nil)
.replacingOccurrences(of: "ä", with: "a", options: .literal, range: nil)
.replacingOccurrences(of: "ö", with: "o", options: .literal, range: nil)
.replacingOccurrences(of: "ü", with: "u", options: .literal, range: nil)
.lowercased()
let searchTermy = searchTerm
.replacingOccurrences(of: ",", with: "", options: .literal, range: nil)
.replacingOccurrences(of: "ä", with: "a", options: .literal, range: nil)
.replacingOccurrences(of: "ö", with: "o", options: .literal, range: nil)
.replacingOccurrences(of: "ü", with: "u", options: .literal, range: nil)
.lowercased()
if nameA == searchTermy && nameB != searchTermy {
return true
} else if nameA.hasPrefix(searchTermy) && !nameB.hasPrefix(searchTermy) {
return true
} else if nameA.contains(searchTermy) && !nameB.contains(searchTermy) {
return true
} else {
let n = searchTermy.count
for i in 0..<searchTermy.count {
if nameA.hasPrefix(String(searchTermy[..<(n-i)])) && !nameB.hasPrefix(String(searchTermy[..<(n-i)])) {
return true
} else {
return false
}
}
return false
}
}
这是Dart代码:
return stationList.sort((a, b) {
var nameA = a.stopName
.replaceAll(RegExp(','), '')
.replaceAll(RegExp('ä'), 'a')
.replaceAll(RegExp('ö'), 'o')
.replaceAll(RegExp('ü'), 'u')
.toLowerCase();
var nameB = b.stopName
.replaceAll(RegExp(','), '')
.replaceAll(RegExp('ä'), 'a')
.replaceAll(RegExp('ö'), 'o')
.replaceAll(RegExp('ü'), 'u')
.toLowerCase();
var searchTermy = stationName
.replaceAll(RegExp(','), '')
.replaceAll(RegExp('ä'), 'a')
.replaceAll(RegExp('ö'), 'o')
.replaceAll(RegExp('ü'), 'u')
.toLowerCase();
if ((nameA == searchTermy) && (nameB != searchTermy)) {
return 1;
} else if (nameA.startsWith(searchTermy) && !nameB.startsWith(searchTermy)) {
return 1;
} else if (nameA.contains(searchTermy) && !nameB.contains(searchTermy)) {
return 1;
} else {
var n = searchTermy.length;
for (int i = 0; i < searchTermy.length; i++) {
if (nameA.startsWith(searchTermy.substring(0, (n - i))) && !nameB.startsWith(searchTermy.substring(0, (n - i)))) {
return 1;
} else {
return 0;
}
}
return 0;
}
});
答案 0 :(得分:0)
true / false与此处的0/1不同。
Dart排序检查3种不同的东西。
在A
和B
之间进行比较时,我们有3种可能性:
0
。在这种情况下,A
和B
相等> 0
。这意味着A
放在之后 B
< 0
。在这种情况下,A
被放置在{em> B
之前。