tectonicfury tectonicfury - 1 year ago 119
Swift Question

Assigning value to a variable inside an If else block in swift 3

This thing is so basic I am sure its been asked but I can't find it.

I am experimenting in swift 3 playgrounds and I want to run this code:

import UIKit

var optionalVariable: Int? = 32
var anotherVariable: Int
if optionalVariable != nil{
print("This executed")
anotherVariable = 32

It fails to run and I am getting this error:

Playground execution failed: error: chapter4.playground:5:7:
error: variable 'anotherVariable' used before being initialized

So what's wrong? Why can't I use the value of
when I have assigned a value to it?

If I comment out the last line
the code runs and the output is printed as
This executed

Answer Source

Compiler see that there is a path where the anotherVariable is not initialized (when optionalVariable is nil). This could happen if e.g. another thread sets this optional variable to nil. It won't happen in your code but the compiler can't know this. You have to initialize the anotherVariable at some point before you pass it to a function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download