0

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

6
  • You have to show us the original declaration of legs and any subtypes that that refers to. Commented Aug 4, 2016 at 15:41
  • Better use "for in" loops. See stackoverflow.com/documentation/swift/1186/loops/3839/… Commented Aug 4, 2016 at 15:43
  • But he didn't get an Array out of bounds error. He got a nil Optional error Commented Aug 4, 2016 at 15:43
  • 5
    Am I missing something? The length of an array in Swift is count, not length. Commented Aug 4, 2016 at 15:44
  • @BaseZen lol as usual I'm cursing everything from the makers of swift to xcode and in the end it's me who is 100% a dummy. Thanks man, that was it. Too much python. Commented Aug 4, 2016 at 15:46

1 Answer 1

2

length??

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

What is happening?

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.

Accessing the right index

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])
}

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, as you and BaseZen have pointed out to me it's not length lol it's count. I've been coding in python too much. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.