如何根据字母/符号/数字对字符串数组进行排序

时间:2019-10-12 05:52:22

标签: arrays swift sorting

我有一个String数组

let myArray = ["b", "a", "*", "c", "5"]

我想对它进行排序。排序后,排序的字母应排在首位,符号和数字应排在后面。

let sortedArray = myArray.sorted { $0 < $1 }
print(sortedArray) 
//I get ["*", "5", "a", "b", "c"]
//I want ["a", "b", "c", "5", "*"]

编辑:我看到了这个Answer。有什么捷径吗?

1 个答案:

答案 0 :(得分:1)

有一种更好的方法,我编写了此函数,比您链接的函数短得多。希望你喜欢它! :)

func sortCharacters(array : [String]) -> [String] {
    let letters = array.joined().filter {$0.isLetter}.sorted()
    let numbers = array.joined().filter {$0.isNumber}.sorted()
    let symbols = array.joined().filter {!$0.isLetter && !$0.isNumber}.sorted()
    return Array(letters + numbers + symbols).map {String($0)}
}

let chars = ["*", "5", "a", "b", "c"]
print(sortCharacters(array: chars)) //["a", "b", "c", "5", "*"]