I wanted to create an array in Swift that contained the names of every day of the week, e.g. Sunday, Monday, Tuesday, etc. Obviously, I can do something like the following:
let daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", Saturday"]
But the problem was that I also wanted those names to be localized into other languages without having to manually create one for each. I knew that iOS Objective C/Swift supported automatically translating date names using NSDateFormatter, but I wondered if there was a way to achieve what I want without passing and converting actual, specific dates such as "2016-01-01".
Poking around I was able to find some solutions in Objective C, but this is the Swift way for an easy, quick method to get the names of the days of the week into an array, using the weekdaySymbols property.
let dateFormatter = NSDateFormatter()
let daysOfWeek = dateFormatter.weekdaySymbols
print("daysOfWeek array: (daysOfWeek) daysOfWeek = (daysOfWeek)")
The above code would first display the contents of the array, then element 1 (second in the array) would be "Monday".
There was no need to set locale within Swift, at least this is the case for iOS 9.2 using Xcode 7.2. The daysOfWeek array will automatically provide the list of the translated names. You can even, instead of weekdaySymbols, use shortWeekdaySymbols or even veryShortWeekdaySymbols to get the desired result. For example, shortWeekdaySymbols get you:
daysOfWeek array: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
I am curious, however, what those would look like for a language such as Chinese.
The same concept can be applied for month names using monthSymbols. For instance:
let months = dateFormatter.monthSymbols
print("months array: (months)");
months array: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
There is even one for quarters of the year (using quarterSymbols):
["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]
And for Era as well utilizing, you guessed it, eraSymbols:
Long version using longEraSymbols:
["Before Christ", "Anno Domini"]
Perhaps even more importantly, there are AM and PM symbols as well using AMSymbol and PMSymbol properties.
You can read the official Apple iOS Developer documentation for more info and all the properties available for NSDateFormatter.