在 Swift 中真的需要可选项吗?

Are optionals really necessary in Swift?

据我了解,Swift 是 Objective-C 的升级版本,供开发人员在其应用程序中使用。随之而来的一个新概念是 "optional variables," 或任何一种可能不包含任何内容的变量。

在Objective-C中,这几乎是隐含的。您可以将 nil 的值分配给多种变量,但是在 Swift 中,变量 必须是可选的。

例如,这种说法在Objective-C中完全没问题

SKNode *someNode = [SKNode new];
// some methods appear that may change the value of "someNode."
// they are right here. These "methods" might leave "someNode"
// equal to "nil". If not, they might set "someNode" to a node
// equal to a node that exists already.

// check if it's nil.
if (someNode == nil) {
    // code to run if it exists
}
else {
    // code to run if it doesn't exist
}

而在 Swift 中,此代码:

var node = SKNode.new()
// this "node" is created/used like "someNode" is used above.
if node != nil {
     // code that will run if node exists
}
else {
     // code to run if node doesn't exist
}

会报错:

Binary operator '!=' cannot be applied to operands of type 'SKNode' and 'nil'

但是,将 node 的 Swift 初始化更改为此,您将获得黄金,因为您 显式 node 定义为可选。

var node : SKNode? = SKNode.new()

我可以补充一下,这也不起作用:

var node = SKNode?.new()

报错:

'SKNode?.Type' does not have a member named 'new'

为什么节点必须显式定义为可选?

var node : SKNode? = SKNode.new() 中,node 必须 明确地 定义为可选,因为 SKNode.new() 永远不会 return 无。

Swift中类型的目标是保证一旦定义了一个变量,它的类型就永远不会改变,并且该变量将始终具有有效数据。将变量定义为可选变量 (SKNode?) 意味着该变量是一个 Optional<SKNode>,它 NOT 等同于 SKNode(因此 'SKNode?.Type' does not have a member named 'new' )

您收到的错误 Binary operator '!=' cannot be applied to operands of type 'SKNode' and 'nil' 是因为您正在尝试检查非可选值是否为 Optional.None(或 nil),这是完全没有必要的(不可能)检查语言。