Swift - need to sort an array of string days of week

1565 views arrays
4

Swift 4

I have an array that will have random days of the week text in it. For example

var daysOfWeek: [String] = [] // ["Tuesday", "Thursday" , "Sunday", "Friday"]

I want to be able to sort them like: Sunday, Monday, Tuesday, ect...

Im not sure if this is the right approach, but I tried this..

     let dateFormatter = DateFormatter()

    for element in daysOfWeek {

        print(dateFormatter.weekdaySymbols[element])
    }

Which throws an error:

value of optional type '[String]?' must be unwrapped to refer to member 'subscript' of wrapped base type

Im fairly new to Xcode and Swift

Is this the right way to do it? if so, how can I fix the error?

If this isn't the right way to do it, then what is? I appreciate any help

answered question

1 Answer

9

You can create a dictionary like this, that corresponds each string to a numerical value:

let weekDayNumbers = [
    "Sunday": 0,
    "Monday": 1,
    "Tuesday": 2,
    "Wednesday": 3,
    "Thursday": 4,
    "Friday": 5,
    "Saturday": 6,
]

And then you can just sort by this:

weekdays.sort(by: { (weekDayNumbers[$0] ?? 7) < (weekDayNumbers[$1] ?? 7) })

This will order non-weekday strings at the end.

Also note that different areas of the world have a different start of week. They might order things differently.

posted this

Have an answer?

JD

Please login first before posting an answer.