optional - Default value of uninitialized variable/object in Swift -


i'm new here. started learning swift, , when got topic of optionals, started wonder default value of uninitialized variable is.

in java, 'int' gets initialized 0. in c, gets garbage value. what's swift? bit more precise, stored in x, when write "var x: int" ?

also, if uninitialized object "var c: uicolor" can not pointing nil, point to?

non optionals

if declare variable this

var color: uicolor 

the state of variable uninitalized. means compiler not allow read before gets initialized.

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

more

interestingly compiler smart enough check if branches of code initializing variable before gets used.

e.g. code produce error because compiler cannot guarantee color initialised before print(color) 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 other hand if declare variable optional

var color: uicolor? 

it gets initialised nil

print(color) // nil 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -