最简单的方法是使用sorted():
let words = ["Hello", "Bonjour", "Salute", "Ahola"] let sortedWords = words.sorted() print(sortedWords) // ["Ahola", "Bonjour", "Hello", "Salute"]
或者 sort()
var mutableWords = ["Hello", "Bonjour", "Salute", "Ahola"] mutableWords.sort() print(mutableWords) // ["Ahola", "Bonjour", "Hello", "Salute"]
您可以将闭包作为排序参数:
let words = ["Hello", "Bonjour", "Salute", "Ahola"] let sortedWords = words.sorted(isOrderedBefore: { $0 > $1 }) print(sortedWords) // ["Salute", "Hello", "Bonjour", "Ahola"]
尾随闭包的替代语法:
let words = ["Hello", "Bonjour", "Salute", "Ahola"] let sortedWords = words.sorted() { $0 > $1 } print(sortedWords) // ["Salute", "Hello", "Bonjour", "Ahola"]
但是,如果数组中的元素不一致,则会出现意外结果:
let words = ["Hello", "bonjour", "Salute", "ahola"] let unexpected = words.sorted() print(unexpected) // ["Hello", "Salute", "ahola", "bonjour"]
要解决此问题,请对元素的小写版本进行排序:
let words = ["Hello", "bonjour", "Salute", "ahola"] let sortedWords =words.sorted{ $0.lowercased() < $1.lowercased() } print(sortedWords) // ["ahola", "bonjour", "Hello", "Salute"]
或者import Foundation使用NSString的比较方法,例如caseInsensitiveCompare:
let words = ["Hello", "bonjour", "Salute", "ahola"] let sortedWords =words.sorted{ $0.caseInsensitiveCompare($1) == .orderedAscending } print(sortedWords) // ["ahola", "bonjour", "Hello", "Salute"]
或者,使用localizedCaseInsensitiveCompare可以管理变音符号。
要按字符串所包含的数值对字符串进行正确排序,请compare与以下.numeric选项一起使用:
let files = ["File-42.txt", "File-01.txt", "File-5.txt", "File-007.txt", "File-10.txt"] let sortedFiles = files.sorted() { $0.compare($1, options: .numeric) == .orderedAscending } print(sortedFiles) // ["File-01.txt", "File-5.txt", "File-007.txt", "File-10.txt", "File-42.txt"]