swiftsorting

How to sort array of strings by length in reverse/descending order in Swift?


I would like to order a collection of strings in descending order, according to length.

Firstly, I'm not sure if I should be using a set or an array, given that a set is a collection of unordered things and I don't need the elements in the collection to be necessarily in an ordered collection.

I came across the sorted() method and the sorted(by:) method but can't work out how to do the descending order by length - just by alphabetical order.

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

Solution

  • sorted() takes a closure to do the comparison (the > operator is a closure, since all methods are closures). So:

    let descendingStrings = strings.sorted { $0.count > $1.count }