hanachan1026 hanachan1026 - 2 months ago 7x
iOS Question

segmentation fault 11 in swift2

I have no idea why I get this error.

The problem code is here

for i in 0..<itemDataJson?.count {

When I
it prints Optional(1).
What am I doing wrong?

Thank you.


It's printing Optional(1) because the variable itemDataJson is nullable, so the count would therefore have to be nullable, because we don't know if itemDataJson actually has a value.

The main problem that I see in your code is that you are force-unwrapping variables. Force-unwrapping a variable is a code smell (usually, although I do it myself from time to time, but you need to be careful).

When you force unwrap a variable, you need to ask yourself the question, "Do I want the app to crash here if this variable is nil?". If the answer is yes, then using a force unwrap is acceptable, otherwise, you should create a non-nullable variable or if that is not possible, you should use the guard statement in swift.

This could be used like this:

guard let itemDataJson = itemDataJson else {
    // itemDataJson was null do something

You can use the if let construct as well, but be careful of the pyramid of doom if you don't use the if let construct correctly. See here for using it correctly, or use a guard statement.

I would recommend checking out the documentation on optionals if you have not done so already.