简体   繁体   English

如何在Swift中检查undefined或null变量?

[英]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. 如果'goBack'未定义,我想要做的就是执行if语句。 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. 简而言之,我声明'goBack',要求用户输入他们的名字和姓氏,然后继续下一个视图控制器。 That view controller has a back button that brings us back to the first view controller (where I declared 'goBack'). 该视图控制器有一个后退按钮,将我们带回第一个视图控制器(我声明'goBack')。 When the back button is pressed, a 'goBack' string is also passed of "yes". 按下后退按钮时,“goBack”字符串也会传递“是”。 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. 编辑:firstName和lastName是标签,而passFirstName1和passLastName1是来自第二个视图控制器的变量。

"All I want to do is execute the if-statement if 'goBack' is undefined. How can I do that?" “如果'goBack'未定义,我想要做的就是执行if语句。我怎么能这样做?”

To check whether a variable equals nil you can use a pretty cool feature of Swift called an if-let statement : 要检查变量是否等于nil您可以使用Swift的一个非常酷的功能,称为if-let语句

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, ie can we "let" a constant = goBack ? If so, perform the following action." 它本质上是逻辑等价的“我们可以将goBack存储为非可选常量,即我们可以”让“常量= goBack吗?如果是,请执行以下操作。”

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... 然后你需要做的就是编写一个函数来测试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 最后的感叹号用于展开可选项,而不是将变量定义为可选或不可选

"All I want to do is execute the if-statement if 'goBack' is undefined" “如果'goBack'未定义,我想要做的就是执行if语句”

The guard statement (new in Swift 2) allows exactly this. guard声明(Swift 2中的新内容)允许这一点。 If goBack is nil then the else block runs and exits the method. 如果goBack为nil,则else块运行并退出该方法。 If goBack is not nil then localGoBack is available to use following the guard statement. 如果goBack不是nil,那么localGoBack可以在guard语句之后使用。

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): 来自Swift编程语言(Swift 3.1):

Constants and variables created with optional binding in an if statement are available only within the body of the if statement. 在if语句中使用可选绑定创建的常量和变量仅在if语句的主体内可用。 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 . 相反,使用guard语句创建的常量和变量在guard语句后面的代码行中可用,如Early Exit中所述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM