Search code examples
iosswiftsortingcomparatorswift4

Sorting Struct array in Swift 4


I've got the below struct and would like to sort the items within sessions by startTime field. I'm completely lost on how to do this.

I tried:

let sortedArray = sessionsData?.items.sorted{ ($0["startTime"] as! String) < ($1["startTime"] as! String) }

but that just gives me an error about no subscript members?

Any pointers would really be appreciated, thank you.

public struct sessions: Decodable {
  let status: String?
  let start: Int?
  let count: Int?
  let items: [sessionInfo]?
  let itemsCount: Int?
  let multipart: Bool?
  let startTime: Int?
  let endTime: Int?
}


public struct sessionInfo: Decodable {
  let name: String?
  let datalist: String?
  let sessionType: Int?
  let status: Int?
  let backupType: Int?
  let startTime: Int?
  let endTime: Int?
  let owner: String?
  let numOfErrors: Int?
  let numOfWarnings: Int?
  let flags: Int?
}

I tried the below, but get an error:

var sortedArray = sessionsData?.items?.sorted(by: { (lhs, rhs) -> Bool in
        return lhs.startTime < rhs.startTime
    })

error:

Binary operator '<' cannot be applied to two 'Int?' operands

Solution

  • Try below code, it sorts the struct in asc order but it pushes nil timestamps to bottom. if you want nil timestamps to be at top, make all nil checks in below code to return opposite of what i return in below code.

    var sortedArray = sessionsData?.items?.sorted(by: { (lhs, rhs) -> Bool in
    
    if let lhsTime = lhs.startTime, let rhsTime = rhs.startTime {
        return lhs.startTime < rhs.startTime
    }
    
    if lhs.startTime == nil && rhs.startTime == nil {
        // return true to stay at top
        return false
    }
    
    if lhs.startTime == nil {
        // return true to stay at top
        return false
    }
    
    if rhs.startTime == nil {
        // return false to stay at top
        return true
    }
    
    })