斯威夫特如何排序属性值自定义对象的数组 [英] Swift how to sort array of custom objects by property value

查看:108
本文介绍了斯威夫特如何排序属性值自定义对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说,我们有一个名为镜像文件的自定义类和这个类包含两个属性。

lets say we have a custom class named imageFile and this class contains two properties.

class imageFile  {
    var fileName = String()
    var fileID = Int()
}

很多,其中存储在阵列

lots of them stored in Array

var images : Array = []

var aImage = imageFile()
aImage.fileName = "image1.png"
aImage.fileID = 101
images.append(aImage)

aImage = imageFile()
aImage.fileName = "image1.png"
aImage.fileID = 202
images.append(aImage)

问题是:我怎么可以按FILEID'ASC或DESC

question is: how can i sort images array by 'fileID' ASC or DESC?

推荐答案

首先,声明你的数组作为一个类型数组,这样就可以调用方法时,你迭代:

First, declare your Array as a typed array so that you can call methods when you iterate:

var images : [imageFile] = []

然后你可以简单地做:

Then you can simply do:

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

这篇关于斯威夫特如何排序属性值自定义对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆