7

I want to be able to check when my array index goes out of range. The array elements are all strings, so I tried to do something like this but it doesn't work:

if questions[3] != nil {
}

Can someone just show me how to check?

Henry Brown
  • 2,219
  • 8
  • 31
  • 48

1 Answers1

11

Before indexing into the array, you need to check:

  1. The intended index is not below 0
  2. array's count is above the intended index

let intendedIndex: Int = 3

if (intendedIndex >= 0 && questions.count > intendedIndex) {
    // This line will not throw index out of range:
    let question3 = questions[intendedIndex]
}
AamirR
  • 11,672
  • 4
  • 59
  • 73
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    not really Swift specific but obviously a working solution. Was hoping a bit for a Swift specific method or something but guess the is no such thing. – Blue Bot Oct 06 '20 at 09:57
  • 1
    So not to go far away by other links: if (questions.indices.contains(intendedIndex)) { ... } – Neph Muw Oct 13 '22 at 13:06