ios - Swift 中非可选变量可以为 nil 吗?

标签 ios swift option-type

<分区>

我能否在 Swift 中创建一个普通变量(我的意思是非可选变量)并为其分配一个 nil 值,或者在应用程序生命周期的稍后时间,让它成为 nil?

这让我感到困惑,因为与传统的强大编程语言(如 Java 和 C#)相比,它有点奇怪。

最佳答案

不,这在设计上是不可能的。文档中的这段摘录解释了原因:

The concept of optionals doesn’t exist in C or Objective-C. The nearest thing in Objective-C is the ability to return nil from a method that would otherwise return an object, with nil meaning “the absence of a valid object.” However, this only works for objects—it doesn’t work for structures, basic C types, or enumeration values. For these types, Objective-C methods typically return a special value (such as NSNotFound) to indicate the absence of a value. This approach assumes that the method’s caller knows there is a special value to test against and remembers to check for it. Swift’s optionals let you indicate the absence of a value for any type at all, without the need for special constants.

您将可选值描述为一件坏事,而这是我更欣赏该语言的功能之一,因为它可以防止大多数空指针异常错误。

另一个优点是,当函数可以返回非值时( objective-c 中的引用类型为 nil,整数为 -1 等),您不必从可能值的范围中选择一个值某种类型的变量可以有。更不用说这是调用者和函数/方法都必须遵循的约定。

最后,如果你在代码中使用了太多的问号和感叹号,那么你应该考虑可选值是否真的适合这个问题(感谢 @David 的提示),或者在真正需要可选的所有情况下更频繁地利用可选绑定(bind)。

推荐阅读:Optionals

附录

提示:我经常看到在声明变量但不能根据上下文初始化的情况下使用可选值。非可选可变变量不需要在同一行中声明和初始化——允许延迟初始化,前提是变量在初始化之前不被使用。例如:

var x: Int // Variable declared here

for var counter = 0; counter < 10; ++counter {
    println(counter)
}

var array = [1, 2, 3]

// ... more lines of code NOT using the x variable

x = 5 // Variable initialized here

print(x)

希望此功能能让您从代码中删除几个可选值...

关于ios - Swift 中非可选变量可以为 nil 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25871241/

相关文章:

java - 为什么Java的Optional在ifPresent()中不调用Consumer?

c++ - qmap 可选参数的默认值

swift - 强制解包选项和隐式解包选项之间的区别

ios - TableView中, "cell.selected = true "这句话后整个表格都不能再点击了

swift - 我可以在 NSUserDefaults 中存储多少数据?

ios - 如何在从 api 获取数据时在 TableView 中显示第一个数据

ios - "Spotify like"在swift中拖动底部播放器

ios - 如何直接在 swift 类文件中创建到 Table View Controller Scene 的 segue?

ios - 如何恢复消耗品In App Purchases?

iphone - 关于JSONKit analyze的问题