可以说我们有一个名为orderFile的自定义类,该类包含三个属性。
class orderFile {
var name = String()
var id = Int()
var status = String()
}
其中很多存储在数组中
var aOrders : Array = []
var aOrder = orderFile()
aOrder.name = "Order 1"
aOrder.id = 101
aOrder.status = "closed"
aOrders.append(aOrder)
var aOrder = orderFile()
aOrder.name = "Order 2"
aOrder.id = 101
aOrder.status = "open"
aOrders.append(aOrder)
var aOrder = orderFile()
aOrder.name = "Order 2"
aOrder.id = 101
aOrder.status = "cancelled"
aOrders.append(aOrder)
var aOrder = orderFile()
aOrder.name = "Order 2"
aOrder.id = 101
aOrder.status = "confirmed"
aOrders.append(aOrder)
问题是:如何根据打开,确认,关闭和取消的状态对它们进行排序?
最佳答案
您必须提供一个值,以便在排序功能中进行比较时产生适当的排序。
例如:
extension orderFile
{
var statusSortOrder: Int
{ return ["open","confirmed","closed","cancelled"].index(of: status) ?? 0 }
}
let sortedOrders = aOrders.sorted{$0.statusSortOrder < $1. statusSortOrder}