arrays - 如何在 Swift 中按属性值对自定义对象数组进行排序

标签 arrays sorting swift

假设我们有一个名为 imageFile 的自定义类,该类包含两个属性:

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

其中很多都存储在数组中:

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”按升序或降序对图像数组进行排序?

最佳答案

首先,将数组声明为类型化数组,以便在迭代时可以调用方法:

var images : [imageFile] = []

然后你可以简单地这样做:

swift 2

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

swift 3

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

swift 5

images.sorted { $0.fileId > $1.fileID }

上面的示例按降序排列结果。

关于arrays - 如何在 Swift 中按属性值对自定义对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49543716/

相关文章:

linux - cut 中的定界符是什么意思,为什么在此命令中它排序两次?

json - 如何使用 alamofire 或 swift json 将 JSON 数组解析为 Swift 4 中的数组

Java - 读入7个整数,计算重复出现的次数

javascript - 如何在 JS 中将对象转换为数组列表

c - 为什么我不能声明二维数组?

c++ - 处理 vector 时如何为 find 和 find_if 使用正确的指针

algorithm - PostgreSQL 中任意排序的性能如何?

ios - Swift 中的便捷初始化器

ios - 使用容器自动布局

php - 是否总是需要在 foreach 之前使用 "is_array()"?