假设我们有一个名为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'升序或降序?
如果你不使用自定义对象,而是使用值类型来实现可比协议(Int, String等),你可以简单地这样做:
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
首先,将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 }
上面的例子按降序给出了结果。
如果你不使用自定义对象,而是使用值类型来实现可比协议(Int, String等),你可以简单地这样做:
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