Swift如何通过属性值对自定义对象数组进行sorting
可以说我们有一个名为imageFile的自定义类,这个类包含两个属性。
class imageFile { var fileName = String() var fileID = Int() }
很多都存储在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)
问题是:我怎么可以通过'fileID'ASC或DESCsorting图像数组?
首先,将数组声明为一个types数组,以便在迭代时可以调用方法:
var images : [imageFile] = []
那么你可以简单地做:
images.sorted({ $0.fileID > $1.fileID })
上面的例子给出了descsorting顺序
[ 更新为Swift 3sorting(by 🙂 ]这,利用尾随闭包:
images.sorted { $0.fileID < $1.fileID }
在哪里使用<
或>
取决于ASC或DESC。 如果要修改images
数组 ,请使用以下命令:
images.sort { $0.fileID < $1.fileID }
如果你要重复这样做,而且更喜欢定义一个函数,一种方法是:
func sorterForFileIDASC(this:imageFile, that:imageFile) -> Bool { return this.fileID > that.fileID }
然后用作:
images.sort(by: sorterForFileIDASC)
几乎每个人都直截了当地让我展示一下进化:
你可以使用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 })
有关sorting的工作原理的详细说明,请参见sorting函数 。
Swift 3
people = people.sorted(by: { $0.email > $1.email })
在Swift 3.0中
images.sort(by: { (first: imageFile, second: imageFile) -> Bool in first. fileID < second. fileID })
两种select
1)用sortInPlacesorting原始数组
self.assignments.sortInPlace({ $0.order < $1.order }) self.printAssignments(assignments)
2)使用替代数组来存储有序数组
var assignmentsO = [Assignment] () assignmentsO = self.assignments.sort({ $0.order < $1.order }) self.printAssignments(assignmentsO)
你也可以做类似的事情
images = sorted(images) {$0.fileID > $1.fileID}
所以你的图像数组将被存储为sorting
在Swift 4中, Array
有两个方法,分别称为sorted()
和sorted(by:)
。 第一个方法sorted()
具有下面的声明:
返回集合的元素,sorting。
func sorted() -> [Element]
第二种方法, sorted(by:)
,具有以下声明:
返回集合的元素,使用给定的谓词进行sorting,作为元素之间的比较。
func sorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element]
1.按类似对象的升序sorting
如果集合中的元素types符合Comparable
协议,则可以使用sorted()
来按升序对元素进行sorting。 以下Playground代码显示如何使用sorted()
:
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.按类似对象的降序sorting
如果集合中的元素types符合Comparable
协议,则必须使用sorted(by:)
为了按降序对元素进行sorting。
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.按照不可比对象的升序或降序sorting
如果你的集合中的元素types不符合Comparable
协议,你将不得不使用sorted(by:)
来按升序或降序对元素进行sorting。
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] */
请注意,Swift还提供了两个名为sort()
方法,并sort(by:)
sort()
和sort(by:)
如sorted(by:)
如果您需要在原地sorting集合。
如果你要在多个地方对这个数组进行sorting,那么使你的数组types为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]"
如果您不使用自定义对象,而是实现Comparable协议(Int,String等)的值types,则可以简单地执行此操作:
myArray.sort(>) //sort descending order
一个例子:
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
如果你想sorting自定义对象的原始数组。 这是Swift 2.1中的另一种方法
var myCustomerArray = [Customer]() myCustomerArray.sortInPlace {(customer1:Customer, customer2:Customer) -> Bool in customer1.id < customer2.id }
其中id
是一个整数。 您也可以对String
属性使用相同的<
运算符。
您可以通过查看示例来了解更多关于它的用法: Swift2:Near Customers
我这样做,它的工作原理:
var images = [imageFile]() images.sorted(by: {$0.fileID.compare($1.fileID) == .orderedAscending })