1

I have an array of SortedELRStructure that I need to sort by it's elr property, AS WELL AS by it's railwayID. The trouble I am having is the railwayID is populated using a string value, as it could be anything like ["1A", "C0284", "300000"] etc so when I sort the array by railwayID is sorts them as strings and I get back ["101023", "10A", "11", "12", "110032"] (example).

How do I sort an array of this type by the numerical value of railwayID, even when it contains letters, in addition to sorting by the elr string?

I've tried the following so far, which I think getting close but the railway ID is still being sorted as a string:

let sorted = sortedDayListItems.sorted { t1, t2 in
    if t1.elr == t2.elr {
        if t1.railwayID.isInt && t2.railwayID.isInt {
            return Int(t1.railwayID)! < Int(t2.railwayID)!
        } else {
                 
        }
        return t1.railwayID < t2.railwayID
    }
    return (t1.elr != nil) && (t2.elr == nil)
}

struct SortedELRStructure {
    var dataItem: CalendarSurveyDataItem
    var elr: String
    var railwayID: String
}
8
  • 2
    stackoverflow.com/questions/43870101/… ? Commented Nov 3, 2020 at 22:36
  • I did already see that post. They don't specify how to use that to sort by multiple properties, and I can't work that part out. Commented Nov 3, 2020 at 22:44
  • It's not related to "sort by multiple properties", in the end, it's how to compare ralwayID when their elr are the same, and it's exactly the linked question (with multiple answers to adapt maybe to your case, because it's unclear in where "C0284" would go against "B01", before or after it?) Commented Nov 3, 2020 at 22:45
  • So what is the expected result ["10A", "11", "12", "101023", "110032"] ? Commented Nov 3, 2020 at 22:47
  • Yes, that is what I am hoping to achieve Commented Nov 3, 2020 at 22:47

1 Answer 1

1

You just need to create a custom sort method. If ELR elements are equal sort the ralwayID using localized standard compare otherwise just sort by ELR

let sorted = sortedDayListItems.sorted {
    if $0.elr == $1.elr {
        return $0.railwayID.localizedStandardCompare($1.railwayID) == .orderedAscending
    }
    return $0.elr < $1.elr
}
Sign up to request clarification or add additional context in comments.

Comments

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.