-1

I have a JSON get request where I retrieve information about four users and then load four views with their pictures, names, etc.

I also have a function where the user can tap on those views and view more information about them.

However, I need to make sure that the array (randomFour) containing the four users contains actual information for the view they are selecting and is not nil.

I attempted to do this by counting the indexes of the array, but for some reason it isn't preventing it from going through and then crashes because the values are nil.

@objc func loadWriteView(sender: UITapGestureRecognizer) {
    if sender.view == a_view || sender.view == a_pic && randomFour.count >= 1 {
        setupCardWrite(user: randomFour[0])
    } else if sender.view == b_view || sender.view == b_pic && randomFour.count >= 2 {
        setupCardWrite(user: randomFour[1])
    } else if sender.view == c_view || sender.view == c_pic && randomFour.count >= 3 {
        setupCardWrite(user: randomFour[2])
    } else if sender.view == d_view || sender.view == d_pic && randomFour.count >= 4 {
        setupCardWrite(user: randomFour[3])
    }
}

As you can see, I check that the count is greater than a certain value, but then I still sometimes receive this error:

Thread 1: Fatal error: Index out of range

And when inspecting I see:

randomFour = ([Compliments.User]) 0 values  

How can I make sure that the users have been loaded properly?

Levi K
  • 573
  • 1
  • 4
  • 23
  • The answer to this post shows a solution to ensure array indexes are not out of range: https://stackoverflow.com/questions/25329186/safe-bounds-checked-array-lookup-in-swift-through-optional-bindings – Norman Nov 17 '18 at 00:55

1 Answers1

0

Please try using brackets around the first two conditions

if (sender.view == a_view || sender.view == a_pic) && randomFour.count >= 1 
Amy L.
  • 210
  • 2
  • 4
  • 14
  • Ok, thank you. I will try that. Shouldn't the brackets have no effect though? – Levi K Nov 16 '18 at 22:15
  • 1
    @LeviK Without the parentheses, this particular statement is treated as if you wrote `if sender.view == a_view || (sender.view == a_pic && randomFour.count >= 1)` which is clearly not what you intended. Whenever you have a mix of `||` and `&&` in an expression, always use parentheses to avoid any ambiguity. – rmaddy Nov 16 '18 at 22:46
  • Got it, thank you so much! It usually takes a few hundred tests to get the problem, so if it ever happens again, I will let you know. Thank you so much for your time and efforts, I will mark this correct unless it ends up not working – Levi K Nov 16 '18 at 23:23