我正在尝试通过其中一个函数/方法的返回值对对象数组进行排序。我的课程如下:
class Shift{
var Name: String
var Deliveries: [Delivery] = []
var SalesPercentage: Double = 0.0
var LabelForecast: Double = 0.0
var PromotionModsChanging: Double = 0.0
var ShortName: String{
get{
return Name[0...2]
}
}
init(Name: String){
self.Name = Name
}
func getSales() -> Double{
return (SalesPercentage / 100) * Settings.ExpectedWeeklySales
}
func totalWeight() -> Double{
var total: Double = 0.0
// Add total Deliveries Weight
for delivery: Delivery in Deliveries{
total = total + delivery.DeliveryWeight()
}
// Add Sales Weight
total = total + (getSales() * 0.2)
// Add labels Weight measured at 100 labels per hour
total = total + (LabelForecast * 0.6)
// Add Promotion Mods Changing measured at 45 Minutes per mod. Ladder racks and grocery shelving should be classed as 0.5 mods each.
total = total + (PromotionModsChanging * 45)
return total
}
}
它们存储的数组如下:
var Shifts: [Shift] = []
然后我将Shift对象附加到。然后我试图通过totalWeight()函数返回的值找到一种组织Shifts数组的方法。有人可以帮忙吗?
答案 0 :(得分:1)
以下内容将Shift
的数组按升序排序:
let sorted = shifts.sorted { $0.totalWeight() < $1.totalWeight() }
或者,不是创建一个新数组并将已排序的shifts
分配给它;你可以这样排序shifts
:
shifts.sort { $0.totalWeight() < $1.totalWeight() }
请记住,上面的代码只会起作用,因为您已将shifts
声明为变量。