I am trying to print an array of weekdays using the weekdaysymbol – here is my code so far
for i in Weekdaysnumbers {
let calender = Calendar.current
let weekdayIndex = ((Weekdaysnumbers[i!]! - 1) + (calender.firstWeekday - 1)) % 7
varWeekdaysStrings.append(calender.shortWeekdaySymbols[weekdayIndex])
}
The Weekdaysnumbers stores an array of a weekday integers that the user gets to set. I then want to print a string representing it. I set it inside a for loop that goes through the array of Weekdaysnumbers and appends it to the new array. But I get this error message
Thread 1: Fatal error: Index out of range
- how can I get rid of this error? Any help would be great.
3
Answers
I figured out the answer - thanks to the help of @Duncan C I realize my mistake and I did the following to fix my code
You should subtract 1 from the weekday calendar component value before accessing the shortWeekdaysSymbols array.
Values for the weekday calendar component ranges between 1…7 (for the Gregorian calendar) while the shortWeekdaysSymbols array is 0 based indexed.
Your code makes no sense.
the line
for i in Weekdaysnumbers {
Gives you a loop where on each iteration,
i
will contain sequential values from yourWeekdaysnumbers
array.Using
Weekdaysnumbers[i!]
to try to index intoWeekdaysnumbers
with the value ofi
is wrong, and will likely crash with an array index out of bounds error like the one you report.i
contains a value from the array, not an index into the array.Also, do not use force-unwrap at all until you fully understand optionals. Think of the force-unwrap (
!
) operator as the "crash if nil" operator, because that’s what it does.As a final note not related to your crash, variable names in Swift should start with lower-case letters, and should use "camel case", so
Weekdaysnumbers
should be namedweekdaysNumbers
. (Type names and class names should start with an upper-case letter. variable names and function names should start with a lower case letter.) This is a strong convention in Swift.