1

When I fetch data through a GET method in Swift it is presented as an Array:

URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in

                guard let data = data else { return }
                do {

                    let obj: Response = try JSONDecoder().decode(Response.self, from: data)

                    let cit = obj.assetProfile?.city
                    let coun = obj.assetProfile?.country
                    let negociosLocacion = ("\(cit ?? "N/A"), \(coun ?? "N/A")")

                    let object = EObject(marketOpen: (obj.price?.regularMarketOpen?.fmt ?? "N/A"))


                    self.e.append(object)

But how do I create a catch method where if the index is out of range will present a segue, for example, as to not crash the app?

Pablo Picloso
  • 41
  • 1
  • 6
  • 2
    I don't see that you access an array in your code but you can't catch an out of range error, you need to check `count` first yourself before trying to access a certain index of the array. – Joakim Danielson Apr 05 '20 at 20:08
  • Where do I put that in my class? – Pablo Picloso Apr 05 '20 at 22:00
  • 1
    where do you access and array through the index? just do if array.count - 1 >= index { //do whateber} else {//do whatever} – PaFi Apr 05 '20 at 22:06
  • _"Where do I put that in my class? "_ That is impossible to answer since we a) don't know your class b) don't know what array you are talking about and c) don't know in what context you want to do this – Joakim Danielson Apr 06 '20 at 08:14
  • Does this answer your question? [Swift Array - Check if an index exists](https://stackoverflow.com/a/35512668/2108547) – Daniel Storm Apr 06 '20 at 12:01

4 Answers4

5

You can use indices to check if an array contains an index prior to accessing it:

guard myArray.indices.contains(1) else { return }
let value = myArray[1]

Apple documentation: indices

Daniel Storm
  • 18,301
  • 9
  • 84
  • 152
1

You can handle it through various ways for example I am showing you some code snippets below. See what case is similar to yours.

  1. If you are getting items by index from an array then you can avoid array index out of range error like:

    if yourIndex <= yourArray.endIndex {
        //Then do your desired operation by getting items by your index            
    } else {
        //Do not get items by your index because it is out of range. 
        //Do anything else            
    }
    
  2. You can check that your array is empty or not? like:

    if yourArray.isEmpty {
        // Don't do any array item get operations because your array is empty           
    } else {
        // Your array is not empty
    }
    
  3. You can check that at least your array has a fixed number of elements or not? like:

    if yourArray.count >= yourDesiredNumberOfElements {
        // Your array have at least your desired number of elements.
    } else {
        // Your array does not have your desired number of elements.
        // your array has less elements than you desire.
    }
    
Md. Yamin Mollah
  • 1,609
  • 13
  • 26
1

A good solution is to use a safe subscript with returns optional element.

extension Array {
    public subscript(safeIndex index: Int) -> Element? {
        guard index >= startIndex, index < endIndex else {
            return nil
        }

        return self[index]
    }
}
93sauu
  • 3,770
  • 3
  • 27
  • 43
0

In order to check if the index is out of bounds so as to not cause the app to crash and to handle the situation in another way,

if (yourArray.count - 1) >= yourIndex {
   //Not out of bounds, carry on.
} else {
   //This is when your app would crash due to being out of bounds.
}
user13138159
  • 172
  • 9