I'd recommend making a struct holding the type of section it is (Chapters
vs Units
), and holding the number. This will make it possible for your .sorted()
method to properly sort it.
To understand your "erratic" value, it's not all that erratic. It's sorting your strings by alphabetical order, which makes sense. Technically "Chapter 40" is before "Chapter 5" because "4" < "5". We can fix this by using the struct as followed:
struct Section: Comparable {
var type: String! //Could also make this an enum with 2 values: .chapter and .unit.
var sectionNumber: Int!
//This is the function that is called every time a "<" operator is used on two Section objects.
//if the left hand side's sectionNumber (lhs) is less than the right hand side's, then we return "true"
static func < (lhs: Section, rhs: Section) -> Bool {
return lhs.sectionNumber < rhs.sectionNumber
}
//Same thing, but greater than.
static func > (lhs: Section, rhs: Section) -> Bool {
return lhs.sectionNumber > rhs.sectionNumber
}
}
Now, we can run .sorted()
Because remember, all a sorting algorithm relies on is if one number is greater than the other, so we're doing that by implementing our own > and < signs.
var arr = [Section(type: "Chapter", sectionNumber: 5),
Section(type: "Chapter", sectionNumber: 1),
Section(type: "Chapter", sectionNumber: 8),
Section(type: "Chapter", sectionNumber: 10),
Section(type: "Chapter", sectionNumber: 1),
Section(type: "Chapter", sectionNumber: 9),
Section(type: "Unit", sectionNumber: 2)]
arr = arr.sorted()
(This is all assuming Unit is the same thing as Chapter, not sure if that's true).