苹果公司的文件如下:

您可以一起使用if和let来处理可能丢失的值。这些值表示为可选项。可选值要么包含值,要么包含nil,表示该值缺失。在值的类型后面写一个问号(?),将该值标记为可选值。

为什么要使用可选值?


当前回答

在objective C中,没有值的变量等于“nil”(也可以使用与0和false相同的“nil”值),因此可以在条件语句中使用变量(有值的变量与“TRUE”相同,而那些没有值的变量等于“false”)。

Swift通过提供“可选值”来提供类型安全。即,它可以防止因分配不同类型的变量而形成错误。

所以在Swift中,只有条件语句可以提供布尔值。

var hw = "Hello World"

这里,虽然'hw'是一个字符串,但它不能像objective - C那样在if语句中使用。

//This is an error

if hw

 {..}

为此,它需要被创建为,

var nhw : String? = "Hello World"

//This is correct

if nhw

 {..}

其他回答

让我们以NSError为例,如果没有返回错误,你会想让返回Nil是可选的。如果没有错误,给它赋值是没有意义的。

var error: NSError? = nil

这也允许您拥有一个默认值。因此,如果函数没有传递任何东西,你可以为方法设置一个默认值

func doesntEnterNumber(x: Int? = 5) -> Bool {
    if (x == 5){
        return true
    } else {
        return false
    }
}

让我们实验下面的代码游乐场。我希望能明确什么是可选的和使用它的原因。

var sampleString: String? ///Optional, Possible to be nil

sampleString = nil ////perfactly valid as its optional

sampleString = "some value"  //Will hold the value

if let value = sampleString{ /// the sampleString is placed into value with auto force upwraped.

    print(value+value)  ////Sample String merged into Two
}

sampleString = nil // value is nil and the

if let value = sampleString{

    print(value + value)  ///Will Not execute and safe for nil checking
}

//   print(sampleString! + sampleString!)  //this line Will crash as + operator can not add nil

在Swift中,可选类型既可以有值,也可以没有值。可选选项是通过附加?对任何类型:

var name: String?

您可以参考这个链接来深入了解:https://medium.com/@agoiabeladeyemi/ opoptions -in-swift-2b141f12f870

在Swift中,你不能有一个指向nil的变量——既没有指针,也没有空指针。但是在一个API中,你经常希望能够指出一个特定类型的值,或者一个缺乏值的值——例如,我的窗口是否有一个委托,如果有,它是谁?可选的是Swift的类型安全,内存安全的方式来做到这一点。

这很简单。可选(在Swift中)意味着变量/常数可以为空。你可以看到Kotlin语言实现了同样的事情,但从未将其称为“可选”。例如:

var lol: Laugh? = nil

等价于Kotlin:

var lol: Laugh? = null

在Java中是这样的:

@Nullable Laugh lol = null;

在第一个例子中,如果您没有在对象类型前面使用?符号,那么就会出现错误。因为问号意味着变量/常数可以为空,因此被称为可选的。