Search code examples
arraysswiftnull-check

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


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 {
}

Solution

  • if index < myData.count {
      // safe to access 
      let x = myData[index]
    }