I am new to Swift and coding in general. I am trying to get a list of busy periods from multiple events that occur in one day but keep getting "index out of range."
What is wrong here? (I am sorry my code is very messy)
`func busyPeriod() -> [[String:Date]]{
var busylist: [[String: Date]] = []
var eventlist: [[String: Date]] =
[["start": 2023-02-16 09:00:00, "end": 2023-02-16 10:00:00],
["start": 2023-02-16 10:00:00, "end": 2023-02-16 10:15:00]],
["start": 2023-02-16 13:00:00, "end": 2023-02-16 14:00:00]]
if eventlist.count == 1{
return eventlist
}
for i in eventlist.indices{
if i == 0 {
busylist += [["start": eventlist[0]["start"]!, "end": eventlist[0]["end"]!]]
} else {
//This part comes out as Thread 1: Fatal Error: Index out of range
if busylist[-1]["start"]! <= eventlist[i]["start"]!, eventlist[i]["start"]! <= busylist[-1]["end"]! {
busylist[-1]["start"] = min(busylist[-1]["start"]!, eventlist[i]["start"]!)
busylist[-1]["end"] = max(busylist[-1]["end"]!, eventlist[i]["end"]!)
} else {
busylist += [["start": eventlist[i]["start"]!, "end": eventlist[i]["end"]!]]
}}
return busylist
}
What I expect as an outcome:
busylist = [
["start": 2023-02-16 09:00:00, "end": 2023-02-16 10:15:00],
["start": 2023-02-16 13:00:00, "end": 2023-02-16 14:00:00]]