如何在 Swift 中按倒序/降序按长度对字符串数组进行排序?

tim*_*man 1 sorting swift

我想根据长度按降序排列一组字符串。

首先,我不确定我应该使用集合还是数组,因为集合是无序事物的集合,并且我不需要集合中的元素必须位于有序集合中。

我遇到了sorted()方法和sorted(by:)方法,但无法弄清楚如何按长度降序 - 只是按字母顺序。

let strings: Set = ["andy", "ber", "ed", "gerald"]
let descendingStrings = strings.sorted(by: >)
print(descendingStrings)
Run Code Online (Sandbox Code Playgroud)

Rud*_*dog 8

sorted()使用闭包进行比较(>运算符是闭包,因为所有方法都是闭包)。所以:

let descendingStrings = strings.sorted { $0.count > $1.count }
Run Code Online (Sandbox Code Playgroud)