swift someObject == nil 如何实现

以前的编程经验告诉我们判断一个对象是否为空或者是否实例化可以这样

if(someObject == nil){
  //do something }
else{ }

但是在Swift中这样是不行的,然后我在Stackoverflow上找到了答案

http://stackoverflow.com/questions/24314646/swift-with-nil

var s: String? = nil
s === nil // true

The only caveat is that to compare to nil, your variable must able to be nil. This means that it must be an optional, denoted with a ?.

var s: String is not allowed to be nil, so would therefore always returns false when ===compared to nil.

这里提到,如果想对象可能是nil,你的对象必须是optional的。

The documentation states:

=== or “Identical to” means that two constants or variables of class type refer to exactly the same class instance.

== or “Equal to” means that two instances are considered “equal” or “equivalent” in value, for some appropriate meaning of “equal”, as defined by the type’s designer.”

In Swift, there are class types (class) and value types (structs, enums). Int is not a class type, it's a value type. === operator is defined only for class types (and also for Array but that's a special case). 

原文地址:https://www.cnblogs.com/scaptain/p/3873986.html