Swift - best practice to find the longest string at [String] array

Instead of sorting which is O(n log(n)) for a good sort, use max(by:) which is O(n) on Array providing it a closure to compare string lengths:

Swift 4:

For Swift 4 you can get the string length with the count property on String:

let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]

if let max = array.max(by: {$1.count > $0.count}) {
    print(max)
}

Swift 3:

Use .characters.count on String to get the string lengths:

let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]

if let max = array.max(by: {$1.characters.count > $0.characters.count}) {
    print(max)
}

Swift 2:

Use maxElement on Array providing it a closure to compare string lengths:

let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]

if let max = array.maxElement({$1.characters.count > $0.characters.count}) {
    print(max)
}

Note: maxElement is O(n). A good sort is O(n log(n)), so for large arrays, this will be much faster than sorting.


You can use reduce to do this. It will iterate through your array, keeping track of the current longest string, and then return it when finished.

For example:

let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]

if let longestString = array.reduce(Optional<String>.None, combine:{$0?.characters.count > $1.characters.count ? $0:$1}) {
    print(longestString) // "Game Of Thrones is just good"
}

(Note that Optional.None is now Optional.none in Swift 3)

This uses an nil starting value to account for the fact that the array could be empty, as pointed out by @JHZ (it will return nil in that case). If you know your array has at least one element, you can simplify it to:

let longestString = array.reduce("") {$0.characters.count > $1.characters.count ? $0:$1}

Because it only iterates through each element once, it will quicker than using sort(). I did a quick benchmark and sort() appears around 20x slower (although no point in premature optimisation, I feel it is worth mentioning).


Edit: I recommend you go with @vacawama's solution as it's even cleaner than reduce!