Schuey999
Schuey999

Reputation: 4976

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.

Upvotes: 4

Views: 12041

Answers (3)

invisible squirrel
invisible squirrel

Reputation: 3008

"All I want to do is execute the if-statement if 'goBack' is undefined"

The guard statement (new in Swift 2) allows exactly this. If goBack is nil then the else block runs and exits the method. If goBack is not nil then localGoBack is available to use following the guard statement.

var goBack:String?

func methodUsingGuard() {

    guard let localGoBack = goBack else {
        print("goBack is nil")
        return
    }

    print("goBack has a value of \(localGoBack)")
}

methodUsingGuard()

From The Swift Programming Language (Swift 3.1):

Constants and variables created with optional binding in an if statement are available only within the body of the if statement. In contrast, the constants and variables created with a guard statement are available in the lines of code that follow the guard statement, as described in Early Exit.

Upvotes: 1

newshorts
newshorts

Reputation: 1056

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

Upvotes: 1

Lyndsey Scott
Lyndsey Scott

Reputation: 37290

"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."

Upvotes: 7

Related Questions