Roi Mulia Roi Mulia - 7 months ago 83
Swift Question

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

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

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.