FasterThanLlamas FasterThanLlamas -3 years ago 105
Swift Question

Sort array of structs by a member of each

I am compiling data using the following structs:

struct Nursing {

var leftTime: Double
var rightTime: Double
var submissionTime: Date

}

struct Bottle {

var bottleQuantity: Double
var bottleUnits: String
var submissionTime: Date

}

struct Puree {

var pureeQuantity: Double
var pureeType: String
var pureeUnits: String
var submissionTime: Date

}


Then I create arrays of each type using data from elsewhere in the app.

var nursingArray = [Nursing]()
var bottleArray = [Bottle]()
var pureeArray = [Puree]()


I then filter each array for only entries that occurred in the last day.

let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
var todayBottleArray = bottleArray.filter( { ( $0.submissionTime > yesterday! ) } )
var todayNursingArray = nursingArray.filter( { ( $0.submissionTime > yesterday! ) } )
var todayPureeArray = pureeArray.filter( { ( $0.submissionTime > yesterday! ) } )


Finally they all get combined into a single unsorted array.

var unsortedTodayArray: [Any] = []

unsortedTodayArray.append(todayBottleArray)
unsortedTodayArray.append(todayNursingArray)
unsortedTodayArray.append(todayPureeArray)


Here's the question...while I know they're unrelated, the
submissionTime
property appears in all three. How can I sort
unsortedTodayArray
by
submissionTime
?

Answer Source

You can have your struct conform to the same protocol. Something like...

protocol SubmissionTimeable {
    var submissionTime: Date { get set }
}

struct Nursing: SubmissionTimeable {

    var leftTime: Double
    var rightTime: Double
    var submissionTime: Date
}

struct Bottle: SubmissionTimeable {

    var bottleQuantity: Double
    var bottleUnits: String
    var submissionTime: Date
}

struct Puree: SubmissionTimeable {

    var pureeQuantity: Double
    var pureeType: String
    var pureeUnits: String
    var submissionTime: Date
}

Then let your unsorted array be an array of the protocol.

let unsortedArray = [SubmissionTimeable]()

Then you can sort that array with submissionTime.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download