Reputation: 13
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
Upvotes: 0
Views: 128
Reputation: 13
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
for i in Weekdaysnumbers {
switch i {
case 1:
varWeekdaysStrings.append("Sunday")
case 2:
varWeekdaysStrings.append("Monday")
case 3:
varWeekdaysStrings.append("Tuesday")
case 4:
varWeekdaysStrings.append("Wednesday")
case 5:
varWeekdaysStrings.append("Thursday")
case 6:
varWeekdaysStrings.append("Friday")
case 7:
varWeekdaysStrings.append("Saturday")
default:
print("error")
}
Upvotes: 0
Reputation: 344
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.
Upvotes: 1
Reputation: 131491
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 your Weekdaysnumbers
array.
Using Weekdaysnumbers[i!]
to try to index into Weekdaysnumbers
with the value of i
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 named weekdaysNumbers
. (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.
Upvotes: 1