UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

error: variable used before being initialized

Forums > Swift

@Donni  

Here is the code I wrote:

var action1: String
var person3 = "kk"

if person3 == "hater"
{
    action1 = "hate"
}
else if person3 == "player"
{
    action1 = "play"
}
else
{
    action1 = "cruise"
}
// That was Part 1 ^
// Part 2 below:

var action2: String
var stayingOutWayTooLate = true
var absolutlyNothingInBrain = true

if stayingOutWayTooLate  && absolutlyNothingInBrain
{
    action2 = "cruise"
}

if !stayingOutWayTooLate && !absolutlyNothingInBrain
{
    action2 = "Tim McGraw"
}

Swift runs part 1 fine but by part 2 it throws this error:

error: The Main PlayGround.playground:236:1: error: variable 'action2' used before being initialized
action2
^

The Main PlayGround.playground:218:5: note: variable defined here
var action2: String
    ^

I can't figure out what is wrong with the code.

Thank you in advance!

3      

Is there something else in your code that you didn't post? The above works just fine for me, but if I put a print(action2) statement at the end I get the error you are reporting.

I fixed the error by simply using var action2 = "" instead of var action2: String

3      

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.

3      

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 action2.

3      

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

var action2: String
var stayingOutWayTooLate = true
var absolutlyNothingInBrain = true

if stayingOutWayTooLate  && absolutlyNothingInBrain
{
    action2 = "cruise"
} else {
    action2 = "Tim McGraw"
}

3      

@Donni  

Thank you all for the responses.

@roosterboy

Is there something else in your code that you didn't post? The above works just fine for me, but if I put a print(action2) statement at the end I get the error you are reporting.

Yes that's what was causing the error. I'm wondering why should it though. We cleary defined what action2 is gonna be.

I fixed the error by simply using var action2 = "" instead of var action2: String

They gotta put that in the book. Thank you!

@NigelGee I'm sorry I don't understand. Could you elaborate?

@ChrisParkerWA

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".

That's an interesting theory. Its strange though because the Hackin With iOS book states the following:

You can ask Swift to evaluate as many conditions as you want, but they all need to be true in order for Swift to execute the block of code.

To check multiple conditions, use the &&operator – it means "and". For example:

var action: String
var stayOutTooLate =true
var nothingInBrain =true
if stayOutTooLate && nothingInBrain {   
action ="cruise"
}

Because stayOutTooLate and nothingInBrain are both true, the whole condition is true, and action gets set to "cruise." Swift uses something called short-circuit evaluation to boost performance: if it is evaluating multiple things that all need to be true, and the first one is false, it doesn't even bother evaluating the rest.

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 :) .

3      

We cleary defined what action2 is gonna be.

You didn't, though. You defined what would happen if:

  1. true && true
  2. false && false

but you neglected to define what would happen if one is true and the other false. In that case, action2 would never get initialized and thus when you try to use it (like in a print(action2) statement), the compiler will complain.

Check out the result area in these screenshots for proof:

true_and_true false_and_false true_and_false false_and_true

Note how action2 never gets set in the last two examples.

3      

Hi I am going to try and explain what happening to my understanding!

when you set up the var, action has no value and first and second have values (I change the names of the fields to protect this innocent 😜 or to make quicker to type)

var action: String
var first = true
var second = true

@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.

if first  && second
{
    action = "both true"
}
if first  && !second
{
    action = "first - true, second - false"
}
if !first  && second
{
    action = "first - false, second - true"
}
if !first  && !second
{
    action = "both false"
}
print(action)

you can solve this by a number of ways (which some a mentioned above)

  1. Giving a value to var action: String = "" even if it an empty string
  2. To give an else to the last if statement so the compiler will know that there will a value and else if for the rest.
    else if !first  && !second
    {
    action = "both false"
    } else {
    action = "Will not print"
    }

    As you see that that will never print as all the combinations are there

  3. Give the var action: String? and make it an optional then this give you a warning and to quieten the warning you can force uwrap the print(action!), however if this is a simple example and we know that all the combination are covered but if it was not the the app would crash.
  4. Unwrap the optional with a guard let or if let
    if let action = action {
    print(action)
    }

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

3      

PS I was playing around and found this also worked( I think because the compiler will know there is a value to action)

var action: String
var first = true
var second = true

switch first{
case true:
    switch second {
    case true:
        action = "both true"
    case false:
        action = "first - true, second - false"
    }
case false:
    switch second {
    case true:
        action = "first - false, second - true"
    case false:
        action = "both false"
    }
}

print(action)

3      

Hacking with Swift is sponsored by Essential Developer

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.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

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.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.