|
Here is the code I wrote:
Swift runs part 1 fine but by part 2 it throws this error:
I can't figure out what is wrong with the code. Thank you in advance! |
|
Is there something else in your code that you didn't post? The above works just fine for me, but if I put a I fixed the error by simply using |
|
My interpretation on this is that because the if statements are not effective until at runtime, anything below those statements that attempts to read action2 is going to be picked up by the compiler because it does not look inside the if statement and say, "Oh OK, action2 is set there". I could be wrong but that's my take on it. As @roosterboy points out, initialising it when declaring it solves that problem. |
|
Oh yeah, absolutely. But the code as posted won't exhibit that error because there is nothing after the if clauses that tries to use |
|
It to do with the fact that action2 maynot be any of the strings that you put. however if you finish with a else then you do not get error
|
|
Thank you all for the responses. @roosterboy
Yes that's what was causing the error. I'm wondering why should it though. We cleary defined what action2 is gonna be.
They gotta put that in the book. Thank you! @NigelGee I'm sorry I don't understand. Could you elaborate? @ChrisParkerWA
That's an interesting theory. Its strange though because the Hackin With iOS book states the following:
How is the reader supposed to know that action is actually set to cruise if you can't check it? I guess we just have to trust Paul :) . |
|
You didn't, though. You defined what would happen if:
but you neglected to define what would happen if one is Check out the result area in these screenshots for proof:
Note how |
|
Hi I am going to try and explain what happening to my understanding! when you set up the
@roosterboy is correct that you do not have all the combinations however when you use it anywhere the compiler will do not know if there will be a value attached to it, so it will give an error.
you can solve this by a number of ways (which some a mentioned above)
Sorry if it was rather long but optional are tricky and took me a long time to get my head around them. Hopefully that clear and some extra. https://www.hackingwithswift.com/example-code/language/optional-vs-implicitly-unwrapped-optional-whats-the-difference Good Luck |
|
PS I was playing around and found this also worked( I think because the compiler will know there is a value to action)
|
SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.
Sponsor Hacking with Swift and reach the world's largest Swift community!
This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.