Reputation: 164
I am learning swift and am quite surprised at a paradigm, I would like to better understand, about initialization. (please note I am not a professional developer).
In the following code, I get an error at build time on the last line :
Variable 'ex1' used before being initialized
class Example {
var data:Int
init (value: Int){
self.data = value
}
}
var ex1: Example
var ex2: Example
for i in 1...2 {
switch i {
case 1:
ex1 = Example(value: 10)
case 2 :
ex2 = Example(value: 20)
default:
break
}
}
var result = ex1
So, my understanding is that the compiler is not smart enough to understand that ex1 is initialized at execution in the "for" loop before.
Ok fine. So now I have to initialize my variables a priori, to a random value. This seems odd to me, as not initializing them feels as a safety to spot errors.
Now I have to carry a possibly wrong value without warning. Is this the good practice ? Am I missing something ?
Upvotes: 0
Views: 520
Reputation: 7096
It is possible to declare a variable without initializing it immediately and without the compiler complaining. For example:
let ex: Example
if someBoolean {
ex = Example(value: 10)
} else {
ex = Example(value: 20)
}
print(ex) // this should work fine
However, the compiler only knows how to handle this if all declared variables are initialized in all logical paths. In your question, you only initialize one variable in each case of the switch, and neither in the default. You may know that they will all be initialized by the end of the loop, but the compiler isn't smart enough to figure that out.
There's also very few situations where you would want to do that anyway. If you find yourself needing to initialize different variables in different stages of a loop, there's a good chance you're doing something wrong or you could write your code more efficiently. It's hard to say how to simplify your actual code without seeing it, but for the example code you would get the same result by simply immediately initializing both variables.
If you must do it that way, and you know all of the variables will be initialized before they're used but the compiler doesn't, you can use implicitly unwrapped optionals:
var ex1: Example!
var ex2: Example!
// other code is the same
As with all uses of force/implicit unwrapping, this comes with the risk of your app crashing if you made a mistake or forgot an edge case, so I only recommend it if there aren't any other ways of doing it, or if the other ways require excessively complex code.
Upvotes: 2