Swift: How to check a variable exists (esp. index of array)

5.4k Views Asked by At

I'm trying to check whether a variable (or rather a particular index of an array) exists in Swift.

If I use

if let mydata = array[1] {

I get an error if the index has a value, and a crash if it doesn't.

If I use

if array[1] != nil {

I get compiler warnings and/or crashes.

Essentially, I'm just trying to get command line arguments (which are any filename) and check whether they have been included or not. All the examples for command line arguments I've seen use switch/case statements, but to check for known text, rather than varying filenames.

Im still getting Index out of range errors in Xcode with the following:

if arguments.count > 1 {
    var input = arguments[2]
} else {
}
4

There are 4 best solutions below

2
On BEST ANSWER
if index < myData.count {
  // safe to access 
  let x = myData[index]
}
1
On

You can use contains method to check whether a value exists in an array or not.

For example:

let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41]
let hasBigPurchase = expenses.contains { $0 > 100 } // hasBigPurchase is a boolean saying whether the array contains the value or not.

Check its documentation for more information.

0
On

try this:

extension Collection where Indices.Iterator.Element == Index {

    subscript (safe index: Index) -> Generator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

then:

if let value = array[safe: 1] {
    print(value)
}

now you can even do:

textField.text = stringArray[safe: anyIndex]

that would not cause a crash because textField.text can be nil, and [safe:] subscript always returns value if exists or nil if not exists

2
On

Simply, To check for index :

if index < array.count {
// index is exist

let data = array[index]

}