Reputation: 2636
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
Upvotes: 0
Views: 538
Reputation: 59506
First of all what is the type of steps
? If it's an array it does not have a length
property but count
.
Lets take a look at this example snippet of code
let words = ["Hello", "world"]
for i in 0...words.count {
print(words[i])
}
Here words.count
is 2
so the for
is being executed 3 times (i=0, i=1, i=2).
Since arrays indexes begin from 0
, the following elements are available
words[0] // "Hello"
words[1] // "world"
As you can imagine the last execution of the loop (when i=2
) does access words[2]
which does not exists! And this produces a crash.
Now let's take a look at your for loop
for i in 0...steps.length {
print(steps[i])
}
As described in the previous paragraph, over the last loop execution you are accessing an element that does not exists. It should be
for i in 0..<steps.count {
print(steps[i])
}
Even better you could get rid of the indexes and simply write
for step in steps {
print(step)
}
Another syntax, same result of the previous block of code
steps.forEach { step in
print(step)
}
Upvotes: 2