Swift如何按屬性值對自定義對象數組進行排序

本文翻譯自:Swift how to sort array of custom objects by property value

lets say we have a custom class named imageFile and this class contains two properties. 可以說我們有一個名爲imageFile的自定義類,該類包含兩個屬性。

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)

question is: how can i sort images array by 'fileID' ASC or DESC? 問題是:如何按“ fileID” ASC或DESC對圖像數組進行排序?


#1樓

參考:https://stackoom.com/question/1dFJy/Swift如何按屬性值對自定義對象數組進行排序


#2樓

[ Updated for Swift 3 with sort(by:) ] This, exploiting a trailing closure: [ 更新了Swift 3的sort(by :) ],利用了尾隨的閉包:

images.sorted { $0.fileID < $1.fileID }

where you use < or > depending on ASC or DESC, respectively. 在何處分別使用<>取決於ASC或DESC。 If you want to modify the images array , then use the following: 如果要修改images數組 ,請使用以下命令:

images.sort { $0.fileID < $1.fileID }

If you are going to do this repeatedly and prefer to define a function, one way is: 如果要重複執行此操作,並且希望定義一個函數,則一種方法是:

func sorterForFileIDASC(this:imageFile, that:imageFile) -> Bool {
  return this.fileID > that.fileID
}

and then use as: 然後用作:

images.sort(by: sorterForFileIDASC)

#3樓

First, declare your Array as a typed array so that you can call methods when you iterate: 首先,將Array聲明爲類型化數組,以便在迭代時可以調用方法:

var images : [imageFile] = []

Then you can simply do: 然後,您可以簡單地執行以下操作:

Swift 2 迅捷2

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

Swift 3 & Swift 4 & Swift 5 雨燕3&雨燕4&雨燕5

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

The example above gives desc sort order 上面的示例給出了desc排序順序


#4樓

You can also do something like 您也可以做類似的事情

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

so your images array will be stored as sorted 因此您的圖片數組將按排序存儲


#5樓

If you are going to be sorting this array in more than one place, it may make sense to make your array type Comparable. 如果要在一個以上的地方對該數組進行排序,則使數組類型爲Comparable可能有意義。

class MyImageType: Comparable, Printable {
    var fileID: Int

    // For Printable
    var description: String {
        get {
            return "ID: \(fileID)"
        }
    }

    init(fileID: Int) {
        self.fileID = fileID
    }
}

// For Comparable
func <(left: MyImageType, right: MyImageType) -> Bool {
    return left.fileID < right.fileID
}

// For Comparable
func ==(left: MyImageType, right: MyImageType) -> Bool {
    return left.fileID == right.fileID
}

let one = MyImageType(fileID: 1)
let two = MyImageType(fileID: 2)
let twoA = MyImageType(fileID: 2)
let three = MyImageType(fileID: 3)

let a1 = [one, three, two]

// return a sorted array
println(sorted(a1)) // "[ID: 1, ID: 2, ID: 3]"

var a2 = [two, one, twoA, three]

// sort the array 'in place'
sort(&a2)
println(a2) // "[ID: 1, ID: 2, ID: 2, ID: 3]"

#6樓

Nearly everyone gives how directly, let me show the evolvement: 幾乎每個人都給出直接的方式,讓我展示一下演變過程:

you can use the instance methods of Array: 您可以使用Array的實例方法:

// general form of closure
images.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" keyword
images.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 on
images.sortInPlace({ $0.fileID > $1.fileID })

// the simplification of the closure is the same
images = 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 })

For elaborate explanation about the working principle of sort, see The Sorted Function . 有關sort的工作原理的詳細說明,請參見Sorted Function

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章