Search code examples
iosswiftcalendar

Why Calendar.current.shortMonthSymbols returns an empty list?


Why does the below code returns an empty list of array?

let symbols = Calendar.current.shortMonthSymbols //[]

I assumed that there is always 12 elements in the array, so I simply access it:

let selected = symbols[index] //index depends on what month I need.

I have a crash for some devices here, not for every device. Why is this happening?


Solution

  • You can try to initialize your own calendar with specific type. Try this on a playground

    let indianCalendar = Calendar(identifier: .indian)
    
    indianCalendar.shortMonthSymbols // ["Chaitra", "Vaisakha", "Jyaistha", "Asadha", "Sravana", "Bhadra", "Asvina", "Kartika", "Agrahayana", "Pausa", "Magha", "Phalguna"]
    
    var gregorianCalendar = Calendar(identifier: .gregorian)
    gregorianCalendar.locale = Locale(identifier: "en")
    
    gregorianCalendar.shortMonthSymbols // ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    

    The month symbols depend on both calendar identifier and locale. This way you can get the desired result. I couldn't get an empty list, though. Perhaps the current locale on your device is set to some non-standard value and it causes the list to be empty. That might even be a bug in the SDK.