How to check for an undefined or null variable in Swift?
ios, swift, variables, xcode6
Solution
"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."
Problem
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.