NiCk.JaY
NiCk.JaY

Reputation: 141

Default value of uninitialized variable/object in Swift

I'm new here. Just started learning Swift, and when I got to the topic of optionals, I started to wonder what the default value of an uninitialized variable is.

In Java, an 'int' gets initialized to 0. In C, it gets garbage value. So what's with Swift? To be a bit more precise, what is stored in x, when I write "var x: Int" ?

Also, if an uninitialized object "var c: UIColor" can not be pointing to nil, what does it point to?

Upvotes: 2

Views: 7318

Answers (2)

Luca Angeletti
Luca Angeletti

Reputation: 59496

Non optionals

If you declare a variable like this

var color: UIColor

the state of the variable is Uninitalized. This means the compiler will not allow you to read it before it gets initialized.

print(color)
>> error: variable 'color' used before being initialized

More

Interestingly the compiler is smart enough to check if all the branches of your code are initializing the variable before it gets used.

E.g. this code will produce an error because the compiler cannot guarantee that color is initialised before print(color) is executed.

var color: UIColor
let random = arc4random_uniform(10)
if random > 5 {
    color = UIColor.redColor()
}
print(color)
// error: variable 'color' used before being initialized

Optionals

On the other hand if you declare a variable as an optional

var color: UIColor?

it gets initialised with nil

print(color)
// nil

Upvotes: 8

vadian
vadian

Reputation: 285082

Non-optional variables don't have a default value.

You can't use uninitialized variables in Swift anyway. The compiler doesn't let you.

Upvotes: 1

Related Questions