寻找数组的排序
var myArray = ["Dog", "B-1", "C-1", "C-2", "C-3","Home"]按给定的字符串顺序排列。
例如:哪里myCustomString = "DC"
输入阵列:
["Dog","Goat","C-1","C-2","C-3","Home"]预期输出阵列:
["Dog", "C-1".."C-3","B-1","Home"] // sorted by myCustomString variable 发布于 2017-03-25 03:18:04
如果将myCustomString转换为字符数组,则会更容易。使用Swift的String有点麻烦,因为订阅API太笨拙了。有一种方法可以做到:
Swift 3:
var myArray = ["Dog", "B-1", "C-1", "C-2", "C-3","Home"]
let myCustomString = "DC".characters.map { $0 }
myArray.sort { str1, str2 in
let index1 = str1.isEmpty ? nil : myCustomString.index(of: str1[str1.startIndex])
let index2 = str2.isEmpty ? nil : myCustomString.index(of: str2[str2.startIndex])
switch (index1, index2) {
case (nil, nil):
return str1.compare(str2, options: .numeric) == .orderedAscending
case (nil, _):
return false
case (_, nil):
return true
default:
if index1 != index2 {
return index1! < index2!
} else {
return str1.compare(str2, options: .numeric) == .orderedAscending
}
}
}
print(myArray)原来的答案:
myArray拆分为两个子数组:一个包含所有您有订单的元素;另一个用于您没有排序的元素subArray1进行排序subarray2排序subArray1和subArray2连接在一起,生成新的myArray示例:
let myOrder = "DC".characters.map { $0 }
var myArray = ["Dog", "B-1", "C-1", "C-2", "C-3", "Home"]
var subArray1 = [String]()
var subArray2 = [String]()
myArray.forEach {
if $0.isEmpty || !myOrder.contains($0[$0.startIndex]) {
subArray2.append($0)
} else {
subArray1.append($0)
}
}
subArray1.sort { str1, str2 in
let firstChar1 = str1[str1.startIndex]
let firstChar2 = str2[str2.startIndex]
let index1 = myOrder.index(of: firstChar1)!
let index2 = myOrder.index(of: firstChar2)!
if index1 != index2 {
return index1 < index2
} else {
return str1.compare(str2, options: .numeric) == .orderedAscending
}
}
subArray2.sort { $0.compare($1, options: .numeric) == .orderedAscending }
myArray = subArray1 + subArray2
print(myArray)发布于 2017-03-23 10:02:10
1)将"myCustomString“拆分为其字符组件
2)循环数组,将以先前拆分的字符开头的单词添加到自己的数组中。因此,在这个例子中,您将得到3个数组,一个以'D‘开头的字符串,一个以'C’开头的数组,以及其他不满足这两个条件的数组。
3)对每个数组进行单独排序
4)将数组追加到1中。
https://stackoverflow.com/questions/42972614
复制相似问题