1

I have an array like this:

["Novembre", "Mars", "Décembre", "Octobre", "Février", "Janvier"]

How can i sort it so it becomes :

["Décembre", "Novembre", "Octobre", "Mars", "Février", "Janvier"]
4
  • Is this array always going to contain months of the year? Commented Dec 13, 2014 at 2:08
  • Yes it will always be months Commented Dec 13, 2014 at 2:09
  • Are those array items strings "Novembre"? Commented Dec 13, 2014 at 2:12
  • Yes sorry i forgot to put the "" Commented Dec 13, 2014 at 2:14

2 Answers 2

3

Almost the same, but surely it is better to generate the dictionary by rule than to have to type the month names and numbers yourself:

var names:[String] = []
if let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) {
    cal.locale = NSLocale(localeIdentifier: "fr")
    names = cal.monthSymbols as [String]
}
var months : [String:Int] = [:]
for (ix,name) in enumerate(names) {
    months[name] = ix
}
// now we are ready
let data = ["Novembre", "Mars", "Décembre", "Octobre", "Février", "Janvier"]
let result = data.sorted {months[$0.lowercaseString] > months[$1.lowercaseString]}
Sign up to request clarification or add additional context in comments.

1 Comment

And nicely addresses the sorting, too.
0

Calendar month names are not alphabetized so you need to provide the custom sort order value for each month.

var array = ["Novembre", "Mars", "Décembre", "Octobre", "Février", "Janvier"]
var sortedArray = array.sorted({
    let dict = ["Janvier":1,"Février":2,"Mars":3,"Décembre":12,"Novembre":11,"Octobre":10]
    return dict[$0] > dict[$1]
})

println("sorted \(sortedArray)")

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.