我有这三个阵列:
let codesArray = ["de_DE", "en_US", "en-GB", "es_ES"]
let localesArray = ["Deutsch", "English", "English UK", "Español"]
let internationalsArray = ["German", "English", "British English", "Spanish"]
我想根据internationalsArray对internationalsArray和其他人进行排序,以便我获得:
codesArraySorted = [ "en-GB", "en_US", "de_DE", "es_ES"]
localesArraySorted = [ "English UK", "English", "Deutsch", "Español"]
internationalsArraySorted = ["British English", "English", "German", "Spanish"]
我尝试使用sort()
,isOrderedBefore
,但没有成功。
你能给我一个想法吗?
非常感谢!
答案 0 :(得分:2)
您应该将此信息放入自定义结构中。然后,您可以将此结构类型的实例放入数组中并对数组进行排序:
struct Language {
let code: String
let locale: String
let international: String
}
let languages = [
Language(code: "de_DE", locale: "Deutsch", international: "German"),
Language(code: "en_US", locale: "English", international: "English"),
Language(code: "en-GB", locale: "English UK", international: "British English"),
Language(code: "es_ES", locale: "Español", international: "Spanish")
]
let sorted = languages.sort { $0.international < $1.international }
print(sorted)
然后,您可以使用map
方法提取原始信息:
let codesArraySorted = sorted.map { $0.code }
let localesArraySorted = sorted.map { $0.locale }
let internationalsArraySorted = sorted.map { $0.international }
答案 1 :(得分:1)
首先在Swift中,我们不应该在其类型之后命名变量(或常量),所以:
let codes = ["de_DE", "en_US", "en-GB", "es_ES"]
let locales = ["Deutsch", "English", "English UK", "Español"]
let internationals = ["German", "English", "British English", "Spanish"]
现在让我们构建一系列索引,查看codes
应该如何排序
let indexes = codes.enumerate().sort { $0.element < $1.element }.map { $0.index }
indexes
数组包含[0, 2, 1, 3]
,此数组中的i-th
元素表示i-th
的codes
的位置有
现在我们可以根据索引
对每个数组进行排序let sortedCodes = codes.enumerate().sort { indexes[$0.0] < indexes[$1.0] }.map { $0.element }
let sortedLocales = locales.enumerate().sort { indexes[$0.0] < indexes[$1.0] }.map { $0.element }
let sortedInternationals = internationals.enumerate().sort { indexes[$0.0] < indexes[$1.0] }.map { $0.element }
输出
sortedCodes // ["de_DE", "en-GB", "en_US", "es_ES"]
sortedLocales // ["Deutsch", "English UK", "English", "Español"]
sortedInternationals // ["German", "British English", "English", "Spanish"]
那就是它。
答案 2 :(得分:1)
这是另一种方法,可以避免多次排序,并且如果您愿意,还可以更新原始变量:
var codes = ["de_DE", "en_US", "en-GB", "es_ES"]
var locales = ["Deutsch", "English", "English UK", "Español"]
var internationals = ["German", "English", "British English", "Spanish"]
(codes,locales,internationals) = {( $0.map{codes[$0]},
$0.map{locales[$0]},
$0.map{internationals[$0]}
)}
(codes.enumerated().sorted{$0.1<$1.1}.map{$0.0})
[编辑]您可能还想看看这个答案: https://stackoverflow.com/a/35274250/5237560 为了更优雅的符号。