Вы должны использовать dayDictionary[word.description.lowercased()]
вместо dayDictionary[String(word)]
Я пробовал на игровой площадке и добавил несколько print
строк для l oop ->
for word in components {
print("word is: \(word)")
print("components is: \(components)")
print("previous is: \(previous)")
print("dayDictionary is: \(dayDictionary)")
print("item in dayDict is: \(dayDictionary[word.description.lowercased()])")
if previous == "to" {
print("Hi end")
endIndex = dayDictionary[String(word)] ?? -1
break
}
if word == "to" {
print("Hi Start")
startIndex = dayDictionary[previous] ?? -1
continue
}
if let validIndex = dayDictionary[word.description.lowercased()] {
duration += [validIndex]
print("Valid")
}
previous = String(word)
print("---------------------------------------")
}
Тогда вывод:
1st iteration
word is: Set
components is: ["Set", "alarm", "Monday", "to", "Friday"]
previous is:
dayDictionary is: ["tuesday": 1, "wednesday": 2, "saturday": 5, "monday": 0, "thursday": 3, "sunday": 6, "friday": 4]
item in dayDict is: nil
---------------------------------------
2nd iteration
word is: alarm
components is: ["Set", "alarm", "Monday", "to", "Friday"]
previous is: Set
dayDictionary is: ["tuesday": 1, "wednesday": 2, "saturday": 5, "monday": 0, "thursday": 3, "sunday": 6, "friday": 4]
item in dayDict is: nil
---------------------------------------
3rd iteration
word is: Monday
components is: ["Set", "alarm", "Monday", "to", "Friday"]
previous is: alarm
dayDictionary is: ["tuesday": 1, "wednesday": 2, "saturday": 5, "monday": 0, "thursday": 3, "sunday": 6, "friday": 4]
item in dayDict is: Optional(0)
Valid
---------------------------------------
4th iteration
word is: to
components is: ["Set", "alarm", "Monday", "to", "Friday"]
previous is: Monday
dayDictionary is: ["tuesday": 1, "wednesday": 2, "saturday": 5, "monday": 0, "thursday": 3, "sunday": 6, "friday": 4]
item in dayDict is: nil
Hi Start
5th iteration
word is: Friday
components is: ["Set", "alarm", "Monday", "to", "Friday"]
previous is: Monday
dayDictionary is: ["tuesday": 1, "wednesday": 2, "saturday": 5, "monday": 0, "thursday": 3, "sunday": 6, "friday": 4]
item in dayDict is: Optional(4)
Valid
---------------------------------------
Пожалуйста, посмотрите на третью и пятую итерации. Мы могли бы получить предмет от dayDictionary
.