幕布斯6054654
2019-06-19 10:50:04
如何按屬性值對(duì)自定義對(duì)象數(shù)組進(jìn)行排序假設(shè)我們有一個(gè)名為ImageFile的自定義類,這個(gè)類包含兩個(gè)屬性。class imageFile {
var fileName = String()
var fileID = Int()}其中很多存儲(chǔ)在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)問題是:如何根據(jù)“文件ID”ASC或DESC對(duì)圖像數(shù)組進(jìn)行排序?
3 回答

BIG陽
TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
var images : [imageFile] = []
SWIFT 2
images.sorted({ $0.fileID > $1.fileID })
SWIFT 3和SWIFT 4和SWIFT 5
images.sorted(by: { $0.fileID > $1.fileID })

吃雞游戲
TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
images.sorted { $0.fileID < $1.fileID }
<
>
images
images.sort { $0.fileID < $1.fileID }
func sorterForFileIDASC(this:imageFile, that:imageFile) -> Bool { return this.fileID > that.fileID}
images.sort(by: sorterForFileIDASC)

叮當(dāng)貓咪
TA貢獻(xiàn)1776條經(jīng)驗(yàn) 獲得超12個(gè)贊
// 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 })
添加回答
舉報(bào)
0/150
提交
取消