Swift Array - Check if an index exists

Swift

Swift Problem Overview


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

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

Swift Solutions


Solution 1 - Swift

An elegant way in Swift:

let isIndexValid = array.indices.contains(index)

Solution 2 - Swift

Type extension:
extension Collection {

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

}

Using this you get an optional value back when adding the keyword optional to your index which means your program doesn't 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
}

Solution 3 - Swift

Just check if the index is less than the array size:

if 2 < arr.count {
    ...
} else {
    ...
}

Solution 4 - Swift

Add some extension 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: "d"
// or with guard:
guard let anotherItem = ["a", "b", "c", "d"][safe: 3] else {return}
print(anotherItem) // "d"

Enhances readability when doing if let style coding in conjunction with arrays

Solution 5 - Swift

Swift 4 extension:

For me i prefer like method.

// MARK: - Extension Collection

extension Collection {

    /// Get at index object
    ///
    /// - Parameter index: Index of object
    /// - Returns: Element at index or nil
    func get(at index: Index) -> Iterator.Element? {
        return self.indices.contains(index) ? self[index] : nil
    }
}

Thanks to @Benno Kress

Solution 6 - Swift

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

if let str2 = (arr.count > 2 ? arr[2] : nil) as String?

Solution 7 - Swift

the best way.

  let reqIndex = array.indices.contains(index)
  print(reqIndex)

Solution 8 - Swift

Asserting if an array index exist:

This methodology is great if you don't want to add extension sugar:

let arr = [1,2,3]
if let fourthItem = (3 < arr.count ?  arr[3] : nil ) {
     Swift.print("fourthItem:  \(fourthItem)")
}else if let thirdItem = (2 < arr.count ?  arr[2] : nil) {
     Swift.print("thirdItem:  \(thirdItem)")
}
//Output: thirdItem: 3

Solution 9 - Swift

extension Array {
    func isValidIndex(_ index : Int) -> Bool {
        return index < self.count
    }
}

let array = ["a","b","c","d"]

func testArrayIndex(_ index : Int) {

    guard array.isValidIndex(index) else {
        print("Handle array index Out of bounds here")
        return
    }

}

It's work for me to handle indexOutOfBounds.

Solution 10 - Swift

Swift 4 and 5 extension:

As for me I think this is the safest solution:

public extension MutableCollection {
    subscript(safe index: Index) -> Element? {
        get {
            return indices.contains(index) ? self[index] : nil
        }
        set(newValue) {
            if let newValue = newValue, indices.contains(index) {
                self[index] = newValue
            }
        }
    }
}

Example:

let array = ["foo", "bar"]
if let str = array[safe: 1] {
    print(str) // "bar"
} else {
    print("index out of range")
}

Solution 11 - Swift

I believe the existing answers could be improved further because this function could be needed in multiple places within a codebase (code smell when repeating common operations). So thought of adding my own implementation, with reasoning for why I considered this approach (efficiency is an important part of good API design, and should be preferred where possible as long as readability is not too badly affected). In addition to enforcing good Object-Oriented design with a method on the type itself, I think Protocol Extensions are great and we can make the existing answers even more Swifty. Limiting the extension is great because you don’t create code you don’t use. Making the code cleaner and extensible can often make maintenance easier, but there are trade-offs (succinctness being the one I thought of first).

So, you can note that if you'd ONLY like to use the extension idea for reusability but prefer the contains method referenced above you can rework this answer. I have tried to make this answer flexible for different uses.

TL;DR

You can use a more efficient algorithm (Space and Time) and make it extensible using a protocol extension with generic constraints:

extension Collection where Element: Numeric { // Constrain only to numerical collections i.e Int, CGFloat, Double and NSNumber
  func isIndexValid(index: Index) -> Bool {
    return self.endIndex > index && self.startIndex <= index
  }
}

// Usage

let checkOne = digits.isIndexValid(index: index)
let checkTwo = [1,2,3].isIndexValid(index: 2)

Deep Dive

Efficiency

@Manuel's answer is indeed very elegant but it uses an additional layer of indirection (see here). The indices property acts like a CountableRange<Int> under the hood created from the startIndex and endIndex without reason for this problem (marginally higher Space Complexity, especially if the String is long). That being said, the Time Complexity should be around the same as a direct comparison between the endIndex and startIndex properties because N = 2 even though contains(_:) is O(N) for Collections (Ranges only have two properties for the start and end indices).

For the best Space and Time Complexity, more extensibility and only marginally longer code, I would recommend using the following:

extension Collection {
  func isIndexValid(index: Index) -> Bool {
    return self.endIndex > index && self.startIndex <= index
  }
}

Note here how I've used startIndex instead of 0 - this is to support ArraySlices and other SubSequence types. This was another motivation to post a solution.

Example usage:

let check = digits.isIndexValid(index: index)

For Collections in general, it's pretty hard to create an invalid Index by design in Swift because Apple has restricted the initializers for associatedtype Index on Collection - ones can only be created from an existing valid Collection.Index (like startIndex).

That being said, it's common to use raw Int indices for Arrays because there are many instances when you need to check random Array indices. So you may want to limit the method to fewer structs...

Limit Method Scope

You will notice that this solution works across all Collection types (extensibility), but you can restrict this to Arrays only if you want to limit the scope for your particular app (for example, if you don't want the added String method because you don't need it).

extension Array {
  func isIndexValid(index: Index) -> Bool {
    return self.endIndex > index && self.startIndex <= index
  }
}

For Arrays, you don't need to use an Index type explicitly:

let check = [1,2,3].isIndexValid(index: 2)

Feel free to adapt the code here for your own use cases, there are many types of other Collections e.g. LazyCollections. You can also use generic constraints, for example:

extension Collection where Element: Numeric {
  func isIndexValid(index: Index) -> Bool {
    return self.endIndex > index && self.startIndex <= index
  }
}

This limits the scope to Numeric Collections, but you can use String explicitly as well conversely. Again it's better to limit the function to what you specifically use to avoid code creep.

Referencing the method across different modules

The compiler already applies multiple optimizations to prevent generics from being a problem in general, but these don't apply when the code is being called from a separate module. For cases like that, using @inlinable can give you interesting performance boosts at the cost of an increased framework binary size. In general, if you're really into improving performance and want to encapsulate the function in a separate Xcode target for good SOC, you can try:

extension Collection where Element: Numeric {
  // Add this signature to the public header of the extensions module as well.
  @inlinable public func isIndexValid(index: Index) -> Bool {
    return self.endIndex > index && self.startIndex <= index
  }
}

I can recommend trying out a modular codebase structure, I think it helps to ensure Single Responsibility (and SOLID) in projects for common operations. We can try following the steps here and that is where we can use this optimisation (sparingly though). It's OK to use the attribute for this function because the compiler operation only adds one extra line of code per call site but it can improve performance further since a method is not added to the call stack (so doesn’t need to be tracked). This is useful if you need bleeding-edge speed, and you don’t mind small binary size increases. (-: Or maybe try out the new XCFrameworks (but be careful with the ObjC runtime compatibility for < iOS 13).

Solution 12 - Swift

I think we should add this extension to every project in Swift

extension Collection {
    @inlinable func isValid(position: Self.Index) -> Bool {
        return (startIndex..<endIndex) ~= position
    }
    
    @inlinable func isValid(bounds: Range<Self.Index>) -> Bool {
        return (startIndex..<endIndex) ~= bounds.upperBound
    }
    
    @inlinable subscript(safe position: Self.Index) -> Self.Element? {
        guard isValid(position: position) else { return nil }
        return self[position]
    }
    
    @inlinable subscript(safe bounds: Range<Self.Index>) -> Self.SubSequence? {
        guard isValid(bounds: bounds) else { return nil }
        return self[bounds]
    }
}

extension MutableCollection {
    @inlinable subscript(safe position: Self.Index) -> Self.Element? {
        get {
            guard isValid(position: position) else { return nil }
            return self[position]
        }
        set {
            guard isValid(position: position), let newValue = newValue else { return }
            self[position] = newValue
        }
    }
    @inlinable subscript(safe bounds: Range<Self.Index>) -> Self.SubSequence? {
        get {
            guard isValid(bounds: bounds) else { return nil }
            return self[bounds]
        }
        set {
            guard isValid(bounds: bounds), let newValue = newValue else { return }
            self[bounds] = newValue
        }
    }
}

note that my isValid(position:) and isValid(bounds:) functions is of a complexity O(1), unlike most of the answers below, which uses the contains(_:) method which is of a complexity O(n)


Example usage:

let arr = ["a","b"]
print(arr[safe: 2] ?? "nil") // output: nil
print(arr[safe: 1..<2] ?? "nil") // output: nil

var arr2 = ["a", "b"]
arr2[safe: 2] = "c"
print(arr2[safe: 2] ?? "nil") // output: nil
arr2[safe: 1..<2] = ["c","d"]
print(arr[safe: 1..<2] ?? "nil") // output: nil

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchrishaleView Question on Stackoverflow
Solution 1 - SwiftManuelView Answer on Stackoverflow
Solution 2 - SwiftBenno KressView Answer on Stackoverflow
Solution 3 - SwiftAntonioView Answer on Stackoverflow
Solution 4 - SwiftSentry.coView Answer on Stackoverflow
Solution 5 - SwiftYannStephView Answer on Stackoverflow
Solution 6 - SwiftSergey KalinichenkoView Answer on Stackoverflow
Solution 7 - SwiftManish KumarView Answer on Stackoverflow
Solution 8 - SwiftSentry.coView Answer on Stackoverflow
Solution 9 - SwiftPratik SodhaView Answer on Stackoverflow
Solution 10 - SwiftRunesReaderView Answer on Stackoverflow
Solution 11 - SwiftPranav KasettiView Answer on Stackoverflow
Solution 12 - SwiftMendyView Answer on Stackoverflow