假设我们有一个名为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 students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]

students.sort(by: >)

print(students)

彼得Prints:“[””、“科菲Kweku”、“”、“Akosua Abena”、“]”

其他回答

我是这样做的,而且很管用:

var图像=[图像文件]() 图片社。* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

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

var images : [imageFile] = []

然后你可以简单地做:

斯威夫特2

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

斯威夫特3

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

斯威夫特5

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

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

你也可以这样做

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

你的图像数组会以排序的方式存储

斯威夫特3、4、5所示

    struct imageFile  {
        var fileName = String()
        var fileID = Int()
    }
    
    //append objects like this
    var arrImages = [imageFile]()
    arrImages.append(.init(fileName: "Hello1.png", fileID: 1))
    arrImages.append(.init(fileName: "Hello3.png", fileID: 3))
    arrImages.append(.init(fileName: "Hello2.png",fileID: 2))

    
    //array sorting using below code
    let sortImagesArr = arrImages.sorted(by: {$0.fileID < $1.fileID})
    print(sortImagesArr)
    
    //output
    
    imageFile(fileName: "Hello1.png", fileID: 1),
    imageFile(fileName: "Hello2.png", fileID: 2),
    imageFile(fileName: "Hello3.png", fileID: 3)

如果您想对自定义对象的原始数组进行排序。在Swift 2.1中有另一种方法

var myCustomerArray = [Customer]()
myCustomerArray.sortInPlace {(customer1:Customer, customer2:Customer) -> Bool in
    customer1.id < customer2.id
}

其中id为整数。您也可以对String属性使用相同的<操作符。

你可以通过下面的例子了解更多关于它的用法: Swift2:附近的顾客