Swift – 在[String]数组中找到最长字符串的最佳实践

我试图找到在字符串数组中获取最长字符串的最有效方法.例如 :
let array = ["I'm Roi","I'm asking here","Game Of Thrones is just good"]

结果将是 – “权力的游戏是好的”

我尝试过使用maxElement函数,因为它给出了字母思想中的最大字符串(maxElement()).

有什么建议?谢谢!

不要为了良好的排序而对O(n log(n))进行排序,而是使用max(by :),它是Array上的O(n),为它提供一个比较字符串长度的闭包:

斯威夫特4:

对于Swift 4,您可以使用String上的count属性获取字符串长度:

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

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

斯威夫特3:

在String上使用.characters.count来获取字符串长度:

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

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

斯威夫特2:

在Array上使用maxElement,为它提供一个比较字符串长度的闭包:

let array = ["I'm Roi","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)),因此对于大型数组,这将比排序快得多.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...