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

最佳答案

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

var images : [imageFile] = []

然后你可以简单地做:

swift 2

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

swift 3+

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

上面的例子给出了降序的结果。

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

相关文章:

arrays - 反转数组中键、值的顺序转换为哈希

php - 在 PHP 中将数组元素移动到顶部

c# - 按搜索字符串字母顺序 LINQ 开头的名称排序

python - 如何排序(key=lambda x :) implemented behind the scene?

arrays - 替换字符串数组中的特定字符

ios - 通过 SequenceType 循环在 For 中转换条目?

swift - Alamofire下载方法 "Use of undeclared type ´DownloadFileDestination´"

java - Java中如何将一维数组转换为二维数组

c# - 索引越界问题

php - 两行按时间顺序排序