亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何按屬性值對自定義對象數組進行排序

如何按屬性值對自定義對象數組進行排序

幕布斯6054654 2019-06-19 10:50:04
如何按屬性值對自定義對象數組進行排序假設我們有一個名為ImageFile的自定義類,這個類包含兩個屬性。class imageFile  {     var fileName = String()     var fileID = Int()}其中很多存儲在Array中var images : Array = []var aImage = imageFile()aImage.fileName = "image1.png"aImage.fileID = 101images.append(aImage)aImage = imageFile() aImage.fileName = "image1.png"aImage.fileID = 202images.append(aImage)問題是:如何根據“文件ID”ASC或DESC對圖像數組進行排序?
查看完整描述

3 回答

?
BIG陽

TA貢獻1859條經驗 獲得超6個贊

首先,將Array聲明為類型化數組,以便在迭代時調用方法:

var images : [imageFile] = []

然后你可以簡單地做:

SWIFT 2

images.sorted({ $0.fileID > $1.fileID })

SWIFT 3和SWIFT 4和SWIFT 5

images.sorted(by: { $0.fileID > $1.fileID })

上面的例子給出了DESC排序順序


查看完整回答
反對 回復 2019-06-19
?
吃雞游戲

TA貢獻1829條經驗 獲得超7個贊

這是利用尾隨關閉:

images.sorted { $0.fileID < $1.fileID }

在你使用的地方<>分別取決于ASC或DESC。如果要修改images列陣,然后使用以下內容:

images.sort { $0.fileID < $1.fileID }

如果您要重復這樣做,并且更愿意定義一個函數,一種方法是:

func sorterForFileIDASC(this:imageFile, that:imageFile) -> Bool {
  return this.fileID > that.fileID}

然后用作:

images.sort(by: sorterForFileIDASC)


查看完整回答
反對 回復 2019-06-19
?
叮當貓咪

TA貢獻1776條經驗 獲得超12個贊

幾乎每個人都給多么,怎樣讓我直接展示一下它的演變過程:

可以使用Array的實例方法:

// general form of closureimages.sortInPlace({ (image1: imageFile, image2: imageFile) -> Bool in return image1.fileID > image2.fileID })
// types of closure's parameters and return value can be inferred by Swift, so they are omitted along with the return arrow (->)
images.sortInPlace({ image1, image2 in return image1.fileID > image2.fileID })// Single-expression closures can implicitly return the result 
of their single expression by omitting the "return" keywordimages.sortInPlace({ image1, image2 in image1.fileID > image2.fileID })
// closure's argument list along with "in" keyword can be omitted, $0, $1, $2, and so on are used to refer the closure's first, second,

 third arguments and so onimages.sortInPlace({ $0.fileID > $1.fileID })// the simplification of the closure is the sameimages = images.sort
 ({ (image1: imageFile, image2: imageFile) -> Bool in return image1.fileID > image2.fileID })images = images.sort({ image1, image2 in return 
 image1.fileID > image2.fileID })images = images.sort({ image1, image2 in image1.fileID > image2.fileID })images = images.sort({ $0.fileID > 
 $1.fileID })

有關排序工作原理的詳細說明,請參閱排序函數.


查看完整回答
反對 回復 2019-06-19
  • 3 回答
  • 0 關注
  • 741 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號