Reputation: 141
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
Reputation: 59496
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
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
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
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