如何按属性值对自定义对象数组进行排序假设我们有一个名为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个赞
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贡献1829条经验 获得超7个赞
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)
叮当猫咪
TA贡献1776条经验 获得超12个赞
// 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 })
添加回答
举报
0/150
提交
取消