Search code examples
iosnsdateformatter

fatal error: Index out of range without using any array


fatal error: Index out of range withot using any array when i convert date into week day using loop

 func getDayOfWeek(_ today:String) -> String? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        let date = dateFormatter.date(from:today)
        let weekDay = dateFormatter.weekdaySymbols[Calendar.current.component(.weekday, from:date!)]
        return weekDay
    }

Solution

  • Calendar.current.component(.weekday, from:date!) start from 1 to 7, but index of the weekdaySymbols only from 0 to 6, so you have to minus one to get the correct weekday:

    let weekDay = dateFormatter.weekdaySymbols[Calendar.current.component(.weekday, from:date!)-1]
    

    Also should be using if let and optional like the other answer suggest, to avoid crashing