我想对数组进行排序
像这样:let elements = ["S","A","C","C","T","E","E","E","F","S","S","A","A","C"]
我试过这个
var currentElement = ""
var newElements:[String] = []
for element in elements {
if currentElement != element{
currentElement = element
newElements.append(element)
}
}
但是print["S", "A", "C", "T", "E", "F", "S", "A", "C"]
如何将其排序为["A","C","E","F","S","T"]
答案 0 :(得分:5)
let elements = ["S","A","C","C","T","E","E","E","F","S","S","A","A","C"]
let sortedElements = elements.sorted(by: {$0 < $1})
print(sortedElements)
打印:
["A", "A", "A", "C", "C", "C", "E", "E", "E", "F", "S", "S", "S", "T"]
答案 1 :(得分:3)
你想要做的是删除重复项,然后对其进行排序,对吗?
您可以将其转换为Set
,然后拨打sorted()
:
let elements = ["S","A","C","C","T","E","E","E","F","S","S","A","A","C"]
let newElements = Set(elements).sorted() // ["A", "C", "E", "F", "S", "T"]
答案 2 :(得分:0)
你应该使用ComparisonResult按字母顺序对数组进行排序,因为Set(elements).sorted()并且你有小写字符,sort的结果将是错误的。
var elements = ["S","A","C","C","T","E","E","E","F","S","S","A","A","C"]
elements = elements.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }
//the output["A", "A", "A", "C", "C", "C", "E", "E", "E", "F", "S", "S", "S", "T"]