tryingtolearn tryingtolearn - 4 months ago 17
iOS Question

Optional value in array

Can someone explain to me why this code here returns the error:
"fatal error: unexpectedly found nil while unwrapping an Optional value"

if let steps = legs[0]["steps"] {
for i in 0...steps.length {
print(steps[i])
}
}


while this code:

let steps = legs[0]["steps"]!
print(steps[0])


returns the desired output? I am very confused as I have not been able to get all the values of steps contained in an array somehow..

Similarly:

for i in 0...legs[0]["steps"]!.length {
print(legs[0]["steps"]![i]["start_location"])
}


gets fatal error while:

print(legs[0]["steps"]![0]["start_location"])


returns an optional value

Answer

length??

First of all what is the type of steps? If it's an array it does not have a length property but count.

Accessing the right index

Next, this for loop

for i in 0...steps.length {
    print(steps[i])
}

is exceeding the size of the array, you should not access the steps.length (.count actually) element so it should be

for i in 0..<steps.count {
    print(steps[i])
}

For in

Even better you could get rid of the indexes and simply write

for step in steps {
    print(step)
}

For each

Another syntax, same result of the previous block of code

steps.forEach { step in
    print(step)
}