StuartM
StuartM

Reputation: 6813

Use of unresolved identifier in Swift

I am trying to create an if statement or a switch statement and created a variable to be used.

    if (randomIcon == 1) {
        var coolCircle = TapCircleIcon(typeOfCircle: CircleType.Circle1)
    }

    addChild(coolCircle)

The issue I get is unresolved identifier for coolCircle. This is kind of expected, but I am not sure what the swift equvilant would be.

In Obj-C I would probably set the pointer to nil, then create it if the value exists. How would I get this to parse correctly in Swift. What should I do to set the variable to TapCircleIcon class, but not create an object until the if/switch statement?

Upvotes: 0

Views: 896

Answers (2)

LinusG.
LinusG.

Reputation: 28892

Since the other answers don't explain anything:

You declare the variable coolCircle inside the if block which makes it available to that if block only. That means you will not be able to use it outside again.
I would go with what @fluidsonic's answer to fix the problem.

Hope that helps your understanding :)

Upvotes: 1

fluidsonic
fluidsonic

Reputation: 4676

Simpler:

if (randomIcon == 1) {
    let coolCircle = TapCircleIcon(typeOfCircle: CircleType.Circle1)
    addChild(coolCircle)
}

More flexible:

let coolCircle: TapCircleIcon?
if (randomIcon == 1) {
    coolCircle = TapCircleIcon(typeOfCircle: CircleType.Circle1)
}
else {
    coolCircle = nil  // or something else
}

if let coolCircle = coolCircle {  // not nil
   addChild(coolCircle)
}

Upvotes: 4

Related Questions