hbu*_*ull 4 null objective-c swift
nil 在 Objective-C 和 Swift 中是相似但不同的概念。
在 Objective-C 中
nil缺少 Objective-C 对象。详细来说,id是任意对象的指针。
nil这id表明什么也没有。
因此,任何原始类型都不能为 nils
例如。
NSString *a = nil (o)
int a = nil (x)
Run Code Online (Sandbox Code Playgroud)
在斯威夫特
nil表示不存在任何数据类型,这称为可选。所以nil是一种可选的类型别名吗?
两种语言,任意nil类型的对象都可以调用函数。
例如。
NSString *name = nil;
[a lowercaseString];
let name: String? = nil
name.lowercased()
Run Code Online (Sandbox Code Playgroud)
这两种情况都不会发生空点异常。
不存在任何类型且不存在任何类型怎么能调用函数呢?
nil is kind of typealias of Optional?
No. nil is syntactic sugar for Optional<T>.none where T is the type wrapped by the optional.
name: String? = nil
name.lowercased()
Run Code Online (Sandbox Code Playgroud)
No this is illegal. If you try it in playground, autocomplete will insert a question mark
name?.lowercased()
// ^ here
Run Code Online (Sandbox Code Playgroud)
which basically means if name is not nil, unwrap it and call lowercased() otherwise return nil.
nil in Objective-C and nil in Swift are fundamentally different "under the hood". nil in Objective-C is merely a null pointer. This is why primitives in Objective-C cannot be nil: they are not pointer types.
If you try to send a message to nil in Objective-C, it sort of works because the message sending function checks the receiver and if it is nil it just returns 0, whic will be interpreted by the caller depending on the return type it is expecting e.g. if it expects an int, it will get 0, if it expects a Bool it will get false, if it expects an id, it will get nil.
nil in Swift, as stated above, nil is syntactic sugar for one value of the Optional enum.
enum Optional<T>
{
case some(T)
case none
}
Run Code Online (Sandbox Code Playgroud)
可选本身就是一种类型,您无法调用其包装类型的方法,这就是为什么您必须首先使用 ? 解开它的原因。后修复操作员。
| 归档时间: |
|
| 查看次数: |
1529 次 |
| 最近记录: |