Swift is best practice for finding the longest string in an array [String]

I am trying to find the most efficient way to get the longest string in an array of strings. For instance:

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

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

I tried using maxElementfunc so that it gives the maximum string in alphabetical ideas ( maxElement()).

Any suggestions? Thank!

+4
source share
3 answers

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

Swift 4:

Swift 4 count 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:

.characters.count String, :

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:

maxElement , :

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)
}

: maxElement - O (n). - O (n log (n)), , .

+21

reduce . , , .

:

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"
}

( , Optional.None Optional.None Swift 3)

nil , , @JHZ ( nil). , , :

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

, , sort(). , sort() 20 ( , , ).


: @vacawama, , reduce!

+5

Here you go:

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

var sortedArr = array.sort() { $0.characters.count > $1.characters.count }

let longestEelement = sortedArr[0]
+4
source

All Articles