gpt4 book ai didi

arrays - Swift:按函数值对对象排序

转载 作者:行者123 更新时间:2023-11-28 07:06:58 24 4
gpt4 key购买 nike

我正在尝试根据其中一个函数/方法的返回值对对象数组进行排序。我的类(class)如下:

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 数组。谁能帮忙?

最佳答案

以下将对 Shift 的数组进行升序排序:

let sorted = shifts.sorted { $0.totalWeight() < $1.totalWeight() }

或者,不是创建一个新数组并将排序后的 shifts 分配给它;你可以像这样对 shifts 进行排序:

shifts.sort { $0.totalWeight() < $1.totalWeight() }

请记住,上面的代码只有在您将 shifts 声明为变量时才有效。

关于arrays - Swift:按函数值对对象排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30154559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com