Swift Array - check for an index

In Swift, is there a way to check if an index exists in an array without generating a fatal error?

I was hoping I could do something like this:

let arr: [String] = ["foo", "bar"] let str: String? = arr[1] if let str2 = arr[2] as String? { // this wouldn't run println(str2) } else { // this would be run } 

But I get

fatal error: array index out of range

+46
swift
Sep 22 '14 at 14:46
source share
5 answers

Elegant way in Swift:

 let isIndexValid = array.indices.contains(index) 
+192
Feb 19 '16 at 18:45
source share

Just check if the index is smaller than the size of the array:

 if 2 < arr.count { ... } else { ... } 
+24
Sep 22 '14 at
source share

Swift extension 3 and 4:

 extension Collection { subscript(optional i: Index) -> Iterator.Element? { return self.indices.contains(i) ? self[i] : nil } } 

Using this, you return an optional value when you add a keyword optional to your index, which means that your program does not crash, even if the index is out of range. In your example:

 let arr = ["foo", "bar"] let str1 = arr[optional: 1] // --> str1 is now Optional("bar") if let str2 = arr[optional: 2] { print(str2) // --> this still wouldn't run } else { print("No string found at that index") // --> this would be printed } 
+13
May 01 '17 at 1:41 pm
source share

Add extra sugar:

 extension Collection { subscript(safe index: Index) -> Iterator.Element? { guard indices.contains(index) else { return nil } return self[index] } } if let item = [a,b,c,d][safe:3] {print(item)}//Output: c 

Improves readability when executing if let style in combination with arrays

+5
Apr 20 '17 at 10:24
source share

You can rewrite this in a safer way to check the size of the array and use the ternary conditional:

 if let str2 = (arr.count > 2 ? arr[2] : nil) as String? 
+4
Sep 22 '14 at
source share



All Articles