为什么以下不能在
Swift工作?
if someObject === nil { }
您必须使用==操作符进行测试,例如
if someObject == nil { }
我以为===更像是确保完全相同(基本上比较指针)和==的实例更像isEqual检查.因此,我会认为===将更适合测试对零,但我显然不正确.
文件规定:
=== 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.”
它的工作原理就像你所期望的:
var s: String? = nil s === nil // true
唯一需要注意的是,与nil进行比较,您的变量必须能够为零.这意味着它必须是可选的,用?表示?
var s:字符串不允许为零,所以当===相对于nil时总是返回false.