Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for an undefined or null variable in Swift?

Here's my code:

var goBack: String!

if (goBack == "yes")
    {
        firstName.text = passFirstName1
        lastName.text = passLastName1
    }

All I want to do is execute the if-statement if 'goBack' is undefined. How can I do that? (I don't know what to put in the blank)

The overall program is more complicated which is why I need the variable to be undefined at first. In short, I'm declaring 'goBack', asking the user to type in their first and last name, then continuing to the next view controller. That view controller has a back button that brings us back to the first view controller (where I declared 'goBack'). When the back button is pressed, a 'goBack' string is also passed of "yes". I also passed the first and last name to the next view controller but now I want to pass it back. I'm able to pass it back, its just a matter of making the text appear.

EDIT: firstName and lastName are labels while passFirstName1 and passLastName1 are variables from the second view controller.

like image 448
Schuey999 Avatar asked Feb 12 '23 12:02

Schuey999


2 Answers

"All I want to do is execute the if-statement if 'goBack' is undefined. How can I do that?"

To check whether a variable equals nil you can use a pretty cool feature of Swift called an if-let statement:

if let goBackConst = goBack {
    firstName.text = passFirstName1
    lastName.text = passLastName1
}

It's essentially the logical equivalent of "Can we store goBack as a non-optional constant, i.e. can we "let" a constant = goBack? If so, perform the following action."

like image 111
Lyndsey Scott Avatar answered Feb 16 '23 01:02

Lyndsey Scott


It's really interesting, you can define a variable as optional, which means it may or may not be defined, consider the following scenerio:

you want to find out if the app has been installed before...

let defaults = NSUserDefaults()
let testInstalled : String? = defaults.stringForKey("hasApplicationLaunchedBefore")
if defined(testInstalled) {
    NSLog("app installed already")
    NSLog("testAlreadyInstalled: \(testInstalled)")
    defaults.removeObjectForKey("hasApplicationLaunchedBefore")
} else {
    NSLog("no app")
    defaults.setValue("true", forKey: "hasApplicationLaunchedBefore")
}

Then all you need to do is write a function to test for nil...

func defined(str : String?) -> Bool {
    return str != nil
}

And you've got it. A simpler example might be the following:

if let test : String? = defaults.stringForKey("key") != nil {
    // test is defined
} else {
    // test is undefined
}

The exclamation mark at the end is to for unwrapping the optional, not to define the variable as optional or not

like image 26
newshorts Avatar answered Feb 16 '23 02:02

newshorts