[Swift]数组排序:sort和sorted
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
?微信公眾號:山青詠芝(shanqingyongzhi)
?博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/?)
?GitHub地址:https://github.com/strengthen/LeetCode
?原文地址:https://www.cnblogs.com/strengthen/p/9791288.html?
?如果鏈接不是山青詠芝的博客園地址,則可能是爬取作者的文章。
?原文已修改更新!強(qiáng)烈建議點(diǎn)擊原文地址閱讀!支持作者!支持原創(chuàng)!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
sorted只返回一個(gè)數(shù)組的有序版本,不修改原數(shù)組。
sort無返回值,只會(huì)修改原數(shù)組。
定義一個(gè)需要排序的數(shù)組,其包含元素。示例只初始化一個(gè)Int數(shù)組。
var arr:[Int] = [Int]()最簡數(shù)組排序方法
//升序 arr = arr.sorted(by:<) //降序 arr = arr.sorted(by:>)自定義升序排序方法
1 func sortArray(num1: Int, num2: Int) -> Bool 2 { 3 return num1 < num2 4 }數(shù)組調(diào)用方法
1 //方式1 2 arr.sort(by: sortArray) 3 //方式2 4 arr.sort(by: {(num1: Int, num2: Int) -> Bool in return num1 < num2 })閉包可以不指定參數(shù)類型,編譯器會(huì)進(jìn)行判斷
arr.sort(by: {(num1, num2) in return num1 < num2})可以省略參數(shù)名,直接根據(jù)閉包來引用參數(shù)
arr.sort(by: {return $0 < $1})如果閉包只包含一行語句,可以省略return關(guān)鍵字
arr.sort(by: {$0 < $1})如果閉包是函數(shù)的最后一個(gè)參數(shù),可以將閉包直接放在小括號外面的大括號里。換行也是可選的。
arr.sort(){$0 < $1}甚至可以省略閉包,得最簡形式
arr = arr.sorted(by:<)?sorted()無參數(shù)時(shí)默認(rèn)為升序排序。
Swift的Set類型沒有定義的順序。
要以特定順序迭代集合的值,請使用該sorted()方法,該方法將集合的元素作為使用<運(yùn)算符排序的數(shù)組返回。
1 for genre in favoriteGenres.sorted() { 2 print("\(genre)") 3 } 4 // Classical 5 // Hip hop 6 // Jazz?
轉(zhuǎn)載于:https://www.cnblogs.com/strengthen/p/9791288.html
總結(jié)
以上是生活随笔為你收集整理的[Swift]数组排序:sort和sorted的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: RNN网络【转】
- 下一篇: gitlab+keepalived