简体   繁体   English

swift中的可选参数与Objective-C中的nil指针有何不同?

[英]How optional in swift is different from nil pointer in objective-c?

swift中的可选与目标c中的nil指针有何不同?

Well, 好,

In defintion terms: 在定义上:

Swift optional variable is an enum, which can have nil as a value, where as objective variable is a pointer, where nil represents, it is pointing no where. Swift可选变量是一个枚举,可以将nil作为值,其中,作为目标变量的是指针,其中nil表示,它没有指向任何位置。

In Usage terms: 用语方面:

Both are somewhat similar in the sense, 两者在意义上有些相似,

that both variables having nil value on messaging any method returns nil 在传递任何方法时都具有nil值的两个变量都返回nil

Optional chaining in Swift is similar to messaging nil in Objective-C, but in a way that works for any type, and that can be checked for success or failure. Swift中的可选链接类似于Objective-C中的无消息传递,但是它适用于任何类型,并且可以检查成功或失败。

But in Safety Checking, Swift optional is the winner 但是在安全检查中,Swift可选是赢家

As compiler does many type checking for you already, Ex. 由于编译器已经为您进行了许多类型检查,例如。 non optional parameter can't accept optional, thus you will need to unwrap it by first checking it for nil Or when you you cast any variable, it always returns an optional, thus again a safety feature at compiler level 非可选参数不能接受可选参数,因此您需要首先检查其是否为nil来对其进行拆包,或者当您强制转换任何变量时,它始终返回可选参数,因此也是编译器级别的安全功能

A Swift optional is not a nil value. Swift可选值不是nil值。 It is a sort of enum where one case represents a non-value (similar to NULL in a relational database), and the other represents an actual value. 它是一种枚举,其中一种情况表示非值(类似于关系数据库中的NULL),另一种情况表示实际值。

Writing if myOptional == nil ... is just the syntax for checking if the optional is set to the non-value case. 编写if myOptional == nil ...只是用于检查optional是否设置为非值情况的语法。

A simple proof that the non-value case isn't nil is that optionals apply to all types, including simple integers. 非值情况不为零的一个简单证明是,可选参数适用于所有类型,包括简单整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM