如何按属性值对自定义对象数组排序

时间:2022-01-21 16:45:04

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对图像数组进行排序?

15 个解决方案

#1


600  

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:

然后你可以简单地做:

Swift 2

斯威夫特2

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

Swift 3 & 4

斯威夫特3 & 4

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

The example above gives desc sort order

上面的示例给出了desc排序顺序

#2


174  

[Updated for Swift 3 with sort(by:)] This, exploiting a trailing closure:

[通过sort(by:)对Swift 3进行了更新],利用了一个尾闭包:

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

where you use < or > depending on ASC or DESC, respectively. If you want to modify the images array, then use the following:

使用 <或> 分别取决于ASC或DESC。如果要修改图像数组,请使用以下命令:

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


46  

Nearly everyone gives how directly, let me show the evolvement:

几乎每个人都给出了如何直接,让我展示一下进化:

you can use the instance methods of 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.

有关排序的工作原理的详细说明,请参阅排序函数。

#4


36  

Swift 3

斯威夫特3

people = people.sorted(by: { $0.email > $1.email })

#5


21  

In Swift 3.0

在斯威夫特3.0

images.sort(by: { (first: imageFile, second: imageFile) -> Bool in
    first. fileID < second. fileID
})

#6


17  

Two alternatives

两个选择

1) Ordering the original array with sortInPlace

1)用sortInPlace对原始数组进行排序

self.assignments.sortInPlace({ $0.order < $1.order })
self.printAssignments(assignments)

2) Using an alternative array to store the ordered array

2)使用可选数组存储有序数组

var assignmentsO = [Assignment] ()
assignmentsO = self.assignments.sort({ $0.order < $1.order })
self.printAssignments(assignmentsO)

#7


15  

You can also do something like

你也可以做一些类似的事情。

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

so your images array will be stored as sorted

你的图像数组将被存储为有序。

#8


15  

With Swift 4, Array has two methods called sorted() and sorted(by:). The first method, sorted(), has the following declaration:

对于Swift 4,数组有两种方法,称为排序()和排序(by:)。第一个方法sort()具有以下声明:

Returns the elements of the collection, sorted.

返回已排序的集合的元素。

func sorted() -> [Element]

The second method, sorted(by:), has the following declaration:

第二种方法(按:)排序,有以下声明:

Returns the elements of the collection, sorted using the given predicate as the comparison between elements.

返回集合的元素,使用给定的谓词作为元素之间的比较进行排序。

func sorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element]

1. Sort with ascending order for comparable objects

If the element type inside your collection conforms to Comparable protocol, you will be able to use sorted() in order to sort your elements with ascending order. The following Playground code shows how to use sorted():

如果集合中的元素类型符合可比协议,则可以使用sort()对元素进行升序排序。下面的操场代码展示了如何使用sort ():

class ImageFile: CustomStringConvertible, Comparable {

    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }

    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }

    static func ==(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID == rhs.fileID
    }

    static func <(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID < rhs.fileID
    }

}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted()
print(sortedImages)

/*
 prints: [ImageFile with ID: 100, ImageFile with ID: 200, ImageFile with ID: 300]
 */

2. Sort with descending order for comparable objects

If the element type inside your collection conforms to Comparable protocol, you will have to use sorted(by:) in order to sort your elements with a descending order.

如果集合中的元素类型符合可比协议,则必须使用sort (by:)来按降序对元素进行排序。

class ImageFile: CustomStringConvertible, Comparable {

    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }

    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }

    static func ==(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID == rhs.fileID
    }

    static func <(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID < rhs.fileID
    }

}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted(by: { (img0: ImageFile, img1: ImageFile) -> Bool in
    return img0 > img1
})
//let sortedImages = images.sorted(by: >) // also works
//let sortedImages = images.sorted { $0 > $1 } // also works
print(sortedImages)

/*
 prints: [ImageFile with ID: 300, ImageFile with ID: 200, ImageFile with ID: 100]
 */

3. Sort with ascending or descending order for non-comparable objects

If the element type inside your collection DOES NOT conform to Comparable protocol, you will have to use sorted(by:) in order to sort your elements with ascending or descending order.

如果集合中的元素类型不符合可比协议,则必须使用sort (by:)对元素进行升序或降序排序。

class ImageFile: CustomStringConvertible {

    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }

    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }

}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted(by: { (img0: ImageFile, img1: ImageFile) -> Bool in
    return img0.fileID < img1.fileID
})
//let sortedImages = images.sorted { $0.fileID < $1.fileID } // also works
print(sortedImages)

/*
 prints: [ImageFile with ID: 300, ImageFile with ID: 200, ImageFile with ID: 100]
 */

Note that Swift also provides two methods called sort() and sort(by:) as counterparts of sorted() and sorted(by:) if you need to sort your collection in-place.

注意,Swift还提供了两个方法,称为sort()和sort(by:),作为已排序()和已排序(by:)的对应物(如果需要对集合进行就地排序)。

#9


9  

Swift 2 through 4

斯威夫特2到4

The original answer sought to sort an array of custom objects using some property. Below I will show you a few handy ways to do this same behavior w/ swift data structures!

最初的答案是使用一些属性对自定义对象数组进行排序。下面我将向您展示一些简便的方法来实现相同的行为w/ swift数据结构!

Little things outta the way, I changed ImageFile ever so slightly. With that in mind, I create an array with three image files. Notice that metadata is an optional value, passing in nil as a parameter is expected.

有一些小事情,我对ImageFile做了小小的改动。考虑到这一点,我创建了一个包含三个图像文件的数组。注意,元数据是一个可选值,将nil作为参数传递。

 struct ImageFile {
      var name: String
      var metadata: String?
      var size: Int
    }

    var images: [ImageFile] = [ImageFile(name: "HelloWorld", metadata: nil, size: 256), ImageFile(name: "Traveling Salesmen", metadata: "uh this is huge", size: 1024), ImageFile(name: "Slack", metadata: "what's in this stuff?", size: 2048) ]

ImageFile has a property named size. For the following examples I will show you how to use sort operations w/ properties like size.

ImageFile有一个名为size的属性。对于下面的示例,我将向您展示如何使用诸如大小之类的排序操作。

smallest to biggest size (<)

最小到最大(<)

    let sizeSmallestSorted = images.sorted { (initial, next) -> Bool in
      return initial.size < next.size
    }

biggest to smallest (>)

最大到最小(>)

    let sizeBiggestSorted = images.sorted { (initial, next) -> Bool in
      return initial.size > next.size
    }

Next we'll sort using the String property name. In the same manner, use sort to compare strings. But notice the inner block returns a comparison result. This result will define sort.

接下来,我们将使用字符串属性名进行排序。同样,使用sort来比较字符串。但是请注意,内部块返回比较结果。这个结果将定义sort。

A-Z (.orderedAscending)

a - z(.orderedAscending)

    let nameAscendingSorted = images.sorted { (initial, next) -> Bool in
      return initial.name.compare(next.name) == .orderedAscending
    }

Z-A (.orderedDescending)

Z-A(.orderedDescending)

    let nameDescendingSorted = images.sorted { (initial, next) -> Bool in
      return initial.name.compare(next.name) == .orderedDescending
    }

Next is my favorite way to sort, in many cases one will have optional properties. Now don't worry, we're going to sort in the same manner as above except we have to handle nil! In production;

接下来是我最喜欢的排序方式,在许多情况下,其中一个将具有可选属性。别担心,我们将按照上面的方式排序除了我们必须处理nil!在生产;

I used this code to force all instances in my array with nil property values to be last. Then order metadata using the assumed unwrapped values.

我使用这段代码强制我的数组中所有具有nil属性值的实例保持最后状态。然后使用假定的未包装值对元数据进行排序。

    let metadataFirst = images.sorted { (initial, next) -> Bool in
      guard initial.metadata != nil else { return true }
      guard next.metadata != nil else { return true }
      return initial.metadata!.compare(next.metadata!) == .orderedAscending
    }

It is possible to have a secondary sort for optionals. For example; one could show images with metadata and ordered by size.

有可能对选项进行二次排序。例如;可以显示带有元数据和按大小排序的图像。

#10


6  

If you are going to be sorting this array in more than one place, it may make sense to make your array type 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]"

#11


5  

If you are not using custom objects, but value types instead that implements Comparable protocol (Int, String etc..) you can simply do this:

如果您不使用自定义对象,而是使用实现可比协议(Int, String等)的值类型,您可以简单地这样做:

myArray.sort(>) //sort descending order

An example:

一个例子:

struct MyStruct: Comparable {
    var name = "Untitled"
}

func <(lhs: MyStruct, rhs: MyStruct) -> Bool {
    return lhs.name < rhs.name
}
// Implementation of == required by Equatable
func ==(lhs: MyStruct, rhs: MyStruct) -> Bool {
    return lhs.name == rhs.name
}

let value1 = MyStruct()
var value2 = MyStruct()

value2.name = "A New Name"

var anArray:[MyStruct] = []
anArray.append(value1)
anArray.append(value2)

anArray.sort(>) // This will sort the array in descending order

#12


5  

Swift 4.0. First, I created mutable array of type imageFile() as shown below

斯威夫特4.0。首先,我创建了imageFile()类型的可变数组,如下所示

var arr = [imageFile]()

Create mutable object image of type imageFile() and assign value to properties as shown below

创建imageFile()类型的可变对象映像并为属性赋值,如下所示

   var image = imageFile()
   image.fileId = 14
   image.fileName = "A"

Now, append this object to array arr

现在,将这个对象附加到数组arr

    arr.append(image)

Now, assign the different properties to same mutable object i.e image

现在,将不同的属性赋给相同的可变对象i。e形象

   image = imageFile()
   image.fileId = 13
   image.fileName = "B"

Now, again append image object to array arr

现在,再次向数组arr添加图像对象

    arr.append(image)

Now, we will apply Ascending order on fileId property in array arr objects. Use < symbol for Ascending order

现在,我们将对数组arr对象中的fileId属性应用升序。使用 <符号进行升序< p>

 arr = arr.sorted(by: {$0.fileId < $1.fileId}) // arr has all objects in Ascending order
 print("sorted array is",arr[0].fileId)// sorted array is 13
 print("sorted array is",arr[1].fileId)//sorted array is 14

Now, we will apply Descending order on on fileId property in array arr objects. Use > symbol for Descending order

现在,我们将对数组arr对象中的fileId属性应用降序。使用>符号表示降序

 arr = arr.sorted(by: {$0.fileId > $1.fileId}) // arr has all objects in Descending order
 print("Unsorted array is",arr[0].fileId)// Unsorted array is 14
 print("Unsorted array is",arr[1].fileId)// Unsorted array is 13

In Swift 4.1. For sorted order use

4.1在斯威夫特。顺序使用

let sortedArr = arr.sorted { (id1, id2) -> Bool in
  return id1.fileId < id2.fileId // Use > for Descending order
}

#13


2  

If you want to sort original array of custom objects. Here is another way to do so in Swift 2.1

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

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

Where id is an Integer. You can use the same < operator for String properties as well.

其中id为整数。对于字符串属性也可以使用相同的 <运算符。< p>

You can learn more about its use by looking at an example here: Swift2: Nearby Customers

通过查看这里的一个示例,您可以了解更多关于它的用法:Swift2:附近的客户。

#14


1  

var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]

students.sort(by: >)

print(students)

Prints : "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"

打印:“(“彼得”,“(Kweku”,“科菲”、“Akosua”,“Abena”)”

#15


0  

I do it like this and it works:

我这样做,它是可行的:

var images = [imageFile]() images.sorted(by: {$0.fileID.compare($1.fileID) == .orderedAscending })

var图像= [imageFile]()图像。排序(按:{$0.fileID.compare($1.fileID) = . ordered升序})

#1


600  

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:

然后你可以简单地做:

Swift 2

斯威夫特2

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

Swift 3 & 4

斯威夫特3 & 4

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

The example above gives desc sort order

上面的示例给出了desc排序顺序

#2


174  

[Updated for Swift 3 with sort(by:)] This, exploiting a trailing closure:

[通过sort(by:)对Swift 3进行了更新],利用了一个尾闭包:

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

where you use < or > depending on ASC or DESC, respectively. If you want to modify the images array, then use the following:

使用 <或> 分别取决于ASC或DESC。如果要修改图像数组,请使用以下命令:

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


46  

Nearly everyone gives how directly, let me show the evolvement:

几乎每个人都给出了如何直接,让我展示一下进化:

you can use the instance methods of 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.

有关排序的工作原理的详细说明,请参阅排序函数。

#4


36  

Swift 3

斯威夫特3

people = people.sorted(by: { $0.email > $1.email })

#5


21  

In Swift 3.0

在斯威夫特3.0

images.sort(by: { (first: imageFile, second: imageFile) -> Bool in
    first. fileID < second. fileID
})

#6


17  

Two alternatives

两个选择

1) Ordering the original array with sortInPlace

1)用sortInPlace对原始数组进行排序

self.assignments.sortInPlace({ $0.order < $1.order })
self.printAssignments(assignments)

2) Using an alternative array to store the ordered array

2)使用可选数组存储有序数组

var assignmentsO = [Assignment] ()
assignmentsO = self.assignments.sort({ $0.order < $1.order })
self.printAssignments(assignmentsO)

#7


15  

You can also do something like

你也可以做一些类似的事情。

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

so your images array will be stored as sorted

你的图像数组将被存储为有序。

#8


15  

With Swift 4, Array has two methods called sorted() and sorted(by:). The first method, sorted(), has the following declaration:

对于Swift 4,数组有两种方法,称为排序()和排序(by:)。第一个方法sort()具有以下声明:

Returns the elements of the collection, sorted.

返回已排序的集合的元素。

func sorted() -> [Element]

The second method, sorted(by:), has the following declaration:

第二种方法(按:)排序,有以下声明:

Returns the elements of the collection, sorted using the given predicate as the comparison between elements.

返回集合的元素,使用给定的谓词作为元素之间的比较进行排序。

func sorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element]

1. Sort with ascending order for comparable objects

If the element type inside your collection conforms to Comparable protocol, you will be able to use sorted() in order to sort your elements with ascending order. The following Playground code shows how to use sorted():

如果集合中的元素类型符合可比协议,则可以使用sort()对元素进行升序排序。下面的操场代码展示了如何使用sort ():

class ImageFile: CustomStringConvertible, Comparable {

    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }

    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }

    static func ==(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID == rhs.fileID
    }

    static func <(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID < rhs.fileID
    }

}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted()
print(sortedImages)

/*
 prints: [ImageFile with ID: 100, ImageFile with ID: 200, ImageFile with ID: 300]
 */

2. Sort with descending order for comparable objects

If the element type inside your collection conforms to Comparable protocol, you will have to use sorted(by:) in order to sort your elements with a descending order.

如果集合中的元素类型符合可比协议,则必须使用sort (by:)来按降序对元素进行排序。

class ImageFile: CustomStringConvertible, Comparable {

    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }

    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }

    static func ==(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID == rhs.fileID
    }

    static func <(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID < rhs.fileID
    }

}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted(by: { (img0: ImageFile, img1: ImageFile) -> Bool in
    return img0 > img1
})
//let sortedImages = images.sorted(by: >) // also works
//let sortedImages = images.sorted { $0 > $1 } // also works
print(sortedImages)

/*
 prints: [ImageFile with ID: 300, ImageFile with ID: 200, ImageFile with ID: 100]
 */

3. Sort with ascending or descending order for non-comparable objects

If the element type inside your collection DOES NOT conform to Comparable protocol, you will have to use sorted(by:) in order to sort your elements with ascending or descending order.

如果集合中的元素类型不符合可比协议,则必须使用sort (by:)对元素进行升序或降序排序。

class ImageFile: CustomStringConvertible {

    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }

    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }

}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted(by: { (img0: ImageFile, img1: ImageFile) -> Bool in
    return img0.fileID < img1.fileID
})
//let sortedImages = images.sorted { $0.fileID < $1.fileID } // also works
print(sortedImages)

/*
 prints: [ImageFile with ID: 300, ImageFile with ID: 200, ImageFile with ID: 100]
 */

Note that Swift also provides two methods called sort() and sort(by:) as counterparts of sorted() and sorted(by:) if you need to sort your collection in-place.

注意,Swift还提供了两个方法,称为sort()和sort(by:),作为已排序()和已排序(by:)的对应物(如果需要对集合进行就地排序)。

#9


9  

Swift 2 through 4

斯威夫特2到4

The original answer sought to sort an array of custom objects using some property. Below I will show you a few handy ways to do this same behavior w/ swift data structures!

最初的答案是使用一些属性对自定义对象数组进行排序。下面我将向您展示一些简便的方法来实现相同的行为w/ swift数据结构!

Little things outta the way, I changed ImageFile ever so slightly. With that in mind, I create an array with three image files. Notice that metadata is an optional value, passing in nil as a parameter is expected.

有一些小事情,我对ImageFile做了小小的改动。考虑到这一点,我创建了一个包含三个图像文件的数组。注意,元数据是一个可选值,将nil作为参数传递。

 struct ImageFile {
      var name: String
      var metadata: String?
      var size: Int
    }

    var images: [ImageFile] = [ImageFile(name: "HelloWorld", metadata: nil, size: 256), ImageFile(name: "Traveling Salesmen", metadata: "uh this is huge", size: 1024), ImageFile(name: "Slack", metadata: "what's in this stuff?", size: 2048) ]

ImageFile has a property named size. For the following examples I will show you how to use sort operations w/ properties like size.

ImageFile有一个名为size的属性。对于下面的示例,我将向您展示如何使用诸如大小之类的排序操作。

smallest to biggest size (<)

最小到最大(<)

    let sizeSmallestSorted = images.sorted { (initial, next) -> Bool in
      return initial.size < next.size
    }

biggest to smallest (>)

最大到最小(>)

    let sizeBiggestSorted = images.sorted { (initial, next) -> Bool in
      return initial.size > next.size
    }

Next we'll sort using the String property name. In the same manner, use sort to compare strings. But notice the inner block returns a comparison result. This result will define sort.

接下来,我们将使用字符串属性名进行排序。同样,使用sort来比较字符串。但是请注意,内部块返回比较结果。这个结果将定义sort。

A-Z (.orderedAscending)

a - z(.orderedAscending)

    let nameAscendingSorted = images.sorted { (initial, next) -> Bool in
      return initial.name.compare(next.name) == .orderedAscending
    }

Z-A (.orderedDescending)

Z-A(.orderedDescending)

    let nameDescendingSorted = images.sorted { (initial, next) -> Bool in
      return initial.name.compare(next.name) == .orderedDescending
    }

Next is my favorite way to sort, in many cases one will have optional properties. Now don't worry, we're going to sort in the same manner as above except we have to handle nil! In production;

接下来是我最喜欢的排序方式,在许多情况下,其中一个将具有可选属性。别担心,我们将按照上面的方式排序除了我们必须处理nil!在生产;

I used this code to force all instances in my array with nil property values to be last. Then order metadata using the assumed unwrapped values.

我使用这段代码强制我的数组中所有具有nil属性值的实例保持最后状态。然后使用假定的未包装值对元数据进行排序。

    let metadataFirst = images.sorted { (initial, next) -> Bool in
      guard initial.metadata != nil else { return true }
      guard next.metadata != nil else { return true }
      return initial.metadata!.compare(next.metadata!) == .orderedAscending
    }

It is possible to have a secondary sort for optionals. For example; one could show images with metadata and ordered by size.

有可能对选项进行二次排序。例如;可以显示带有元数据和按大小排序的图像。

#10


6  

If you are going to be sorting this array in more than one place, it may make sense to make your array type 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]"

#11


5  

If you are not using custom objects, but value types instead that implements Comparable protocol (Int, String etc..) you can simply do this:

如果您不使用自定义对象,而是使用实现可比协议(Int, String等)的值类型,您可以简单地这样做:

myArray.sort(>) //sort descending order

An example:

一个例子:

struct MyStruct: Comparable {
    var name = "Untitled"
}

func <(lhs: MyStruct, rhs: MyStruct) -> Bool {
    return lhs.name < rhs.name
}
// Implementation of == required by Equatable
func ==(lhs: MyStruct, rhs: MyStruct) -> Bool {
    return lhs.name == rhs.name
}

let value1 = MyStruct()
var value2 = MyStruct()

value2.name = "A New Name"

var anArray:[MyStruct] = []
anArray.append(value1)
anArray.append(value2)

anArray.sort(>) // This will sort the array in descending order

#12


5  

Swift 4.0. First, I created mutable array of type imageFile() as shown below

斯威夫特4.0。首先,我创建了imageFile()类型的可变数组,如下所示

var arr = [imageFile]()

Create mutable object image of type imageFile() and assign value to properties as shown below

创建imageFile()类型的可变对象映像并为属性赋值,如下所示

   var image = imageFile()
   image.fileId = 14
   image.fileName = "A"

Now, append this object to array arr

现在,将这个对象附加到数组arr

    arr.append(image)

Now, assign the different properties to same mutable object i.e image

现在,将不同的属性赋给相同的可变对象i。e形象

   image = imageFile()
   image.fileId = 13
   image.fileName = "B"

Now, again append image object to array arr

现在,再次向数组arr添加图像对象

    arr.append(image)

Now, we will apply Ascending order on fileId property in array arr objects. Use < symbol for Ascending order

现在,我们将对数组arr对象中的fileId属性应用升序。使用 <符号进行升序< p>

 arr = arr.sorted(by: {$0.fileId < $1.fileId}) // arr has all objects in Ascending order
 print("sorted array is",arr[0].fileId)// sorted array is 13
 print("sorted array is",arr[1].fileId)//sorted array is 14

Now, we will apply Descending order on on fileId property in array arr objects. Use > symbol for Descending order

现在,我们将对数组arr对象中的fileId属性应用降序。使用>符号表示降序

 arr = arr.sorted(by: {$0.fileId > $1.fileId}) // arr has all objects in Descending order
 print("Unsorted array is",arr[0].fileId)// Unsorted array is 14
 print("Unsorted array is",arr[1].fileId)// Unsorted array is 13

In Swift 4.1. For sorted order use

4.1在斯威夫特。顺序使用

let sortedArr = arr.sorted { (id1, id2) -> Bool in
  return id1.fileId < id2.fileId // Use > for Descending order
}

#13


2  

If you want to sort original array of custom objects. Here is another way to do so in Swift 2.1

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

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

Where id is an Integer. You can use the same < operator for String properties as well.

其中id为整数。对于字符串属性也可以使用相同的 <运算符。< p>

You can learn more about its use by looking at an example here: Swift2: Nearby Customers

通过查看这里的一个示例,您可以了解更多关于它的用法:Swift2:附近的客户。

#14


1  

var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]

students.sort(by: >)

print(students)

Prints : "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"

打印:“(“彼得”,“(Kweku”,“科菲”、“Akosua”,“Abena”)”

#15


0  

I do it like this and it works:

我这样做,它是可行的:

var images = [imageFile]() images.sorted(by: {$0.fileID.compare($1.fileID) == .orderedAscending })

var图像= [imageFile]()图像。排序(按:{$0.fileID.compare($1.fileID) = . ordered升序})