Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a variable is not initialized in Swift?

Swift allows variables to be declared but not initialized. How can I check if a variable is not initialized in Swift?

class myClass {}
var classVariable: myClass // a variable of class type - not initialized and no errors!
//if classVariable == nil {} // doesn't work - so, how can I check it?
like image 340
Dmitry Avatar asked Dec 10 '22 20:12

Dmitry


2 Answers

You're right—you may not compare a non-optional variable to nil. When you declare, but do not provide a value for, a non-optional variable, it is not set to nil like an optional variable is. There is no way to test for the use of an uninitialized non-optional variable at runtime, because any possibility of such use is a terrible, compiler-checked programmer error. The only code that will compile is code that guarantees every variable will be initialized before its use. If you want to be able to assign nil to a variable and check its value at runtime, then you must use an optional.

Example 1: Correct Usage

func pickThing(choice: Bool) {
    let variable: String //Yes, we can fail to provide a value here...

    if choice {
        variable = "Thing 1"
    } else {
        variable = "Thing 2"
    }

    print(variable) //...but this is okay because the variable is definitely set by now.
}

Example 2: Compilation Error

func pickThing2(choice: Bool) {
    let variable: String //Yes, we can fail to provide a value here, but...

    if choice {
        variable = "Thing 1"
    } else {
        //Uh oh, if choice is false, variable will be uninitialized...
    }

    print(variable) //...that's why there's a compilation error. Variables ALWAYS must have a value. You may assume that they always do! The compiler will catch problems like these.
}

Example 3: Allowing nil

func pickThing3(choice: Bool) {
    let variable: String? //Optional this time!

    if choice {
        variable = "Thing 1"
    } else {
        variable = nil //Yup, this is allowed.
    }

    print(variable) //This works fine, although if choice is false, it'll print nil.
}
like image 122
andyvn22 Avatar answered Dec 29 '22 12:12

andyvn22


It might be a anomaly of the compiler that you don't get an error declaring a variable this way

class MyClass {}
var myClass : MyClass

but in a Playground you get a runtime error when you just read the variable

myClass

variable 'myClass' used before being initialized

One of the most essential features of Swift is that a non-optional variable can never be nil. If you try to access the variable you'll get a runtime error aka crash.

like image 24
vadian Avatar answered Dec 29 '22 12:12

vadian