1

I'm trying to sort an array of objects by the return value of one of their functions/methods. My class is as below:

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
}


}

The array that they are stored in is as:

var Shifts: [Shift] = []

Which I've then appended Shift objects to. Then I am trying to find a way to organise the Shifts array by the returned value from the totalWeight() function. Can anyone help?

1 Answer 1

1

The following would sort the array of Shifts into ascending order:

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

Alternatively, instead of creating a new array and assigning the sorted shifts to that; you could sort shifts like so:

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

Bear in mind, the immediately above code will only work because you've declared shifts as variable.

Sign up to request clarification or add additional context in comments.

1 Comment

Can't believe it. Tried it already but had a syntax error so wouldn't work. Cheers bro

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.