Swift nil 与 Objective-C nil 不同 [英] Swift nil is not the same as Objective-C nil
问题描述
Apple 文档中提到:
Apple documentation mentions that:
Swift 的 nil 与 Objective-C 中的 nil 不同.在 Objective-C 中,无是指向不存在对象的指针.在 Swift 中,nil 不是指针——它是某种类型的值的缺失.可选的任何类型都可以设置为 nil,而不仅仅是对象类型
Swift’s nil is not the same as nil in Objective-C. In Objective-C, nil is a pointer to a non-existent object. In Swift, nil is not a pointer—it is the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types
以上知识什么时候有用?在适用的情况下,编译器是否会自动将 Swift nil 转换为 Objective-C nil,反之亦然?
When is the above knowledge useful? Will compiler convert Swift nil to Objective-C nil and vice versa automatically where applicable?
推荐答案
是的,编译器会将 Objective-C nils 转换为 Swift nils.这就是为什么在从 Objective-C 转换时,所有指针都必须在 Swift 中成为可选项.
Yes, the compiler will convert Objective-C nils to Swift nils. That is why when translating from Objective-C all pointers must become optionals in Swift.
这些知识的用处在您给出的描述中是正确的:
The usefulness of this knowledge is right in the description you gave:
任何类型的可选项都可以设置为 nil,而不仅仅是对象类型
Optionals of any type can be set to nil, not just object types
在 Swift 中,所有类型都可以是可选的,因此 nil
.例如,在 Objective-C 中,你不能将 NSInteger 设为 nil.
In Swift all types can be made optional and therefore nil
. For example, in Objective-C you cannot make an NSInteger nil.
技术上 nil
只是 Optional 枚举中的一个例子:
Technically nil
is just a case in the Optional enum:
enum Optional<T> {
case None
case Some(T)
}
nil
只是 None
情况的简写
这篇关于Swift nil 与 Objective-C nil 不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!