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

Roi Mulia picture Roi Mulia · Apr 27, 2016 · Viewed 9k times · Source

I'm trying to find what is the most effective way to get the longest string in a string array. For example :

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

and the outcome will be - "Game Of Thrones is just good"

I've tried using the maxElement func, tho it's give the max string in a alphabetic ideas(maxElement()).

Any suggestions? Thanks!

Answer

vacawama picture vacawama · Apr 27, 2016

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.