Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if an array index is out of range SWIFT [duplicate]

Tags:

arrays

swift

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?

like image 726
Henry Brown Avatar asked May 12 '15 18:05

Henry Brown


People also ask

How do you stop an index out of bound exception in Swift?

by checking if array contains that index or not before use it, we can make sure that we will not ever face “Index out of range” (if there's no other thread/async code that changes the array value) because we can make sure that this array is containing index we want to access.

How do you find the index of an element in an array in Swift?

To find the index of a specific element in an Array in Swift, call firstIndex() method and pass the specific element for of parameter. Array. firstIndex(of: Element) returns the index of the first match of specified element in the array. If specified element is not present in the array, then this method returns nil .

How do I check if two arrays are equal in Swift?

To check if two arrays are equal in Swift, use Equal To == operator. Equal To operator returns a Boolean value indicating whether two arrays contain the same elements in the same order. If two arrays are equal, then the operator returns true , or else it returns false .

Which one is faster array or set in Swift?

Difference between an Array and Set in SwiftArray is faster than set in terms of initialization. Set is slower than an array in terms of initialization because it uses a hash process. The array allows storing duplicate elements in it. Set doesn't allow you to store duplicate elements in it.


1 Answers

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]
}
like image 166
Sergey Kalinichenko Avatar answered Nov 14 '22 23:11

Sergey Kalinichenko