• 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). 

  • 相关阅读:
    array与xml转换实现(转)
    设计模式之: 策略模式
    设计模式之: 代理模式
    设计模式之: 状态模式
    dedecms分页
    dedecms导出csv文件
    假如项目中使用到了多 表查询,怎么办?
    git忽略某个文件夹
    git忽略某个文件
    无极限分类
  • 原文地址:https://www.cnblogs.com/scaptain/p/3873986.html
Copyright © 2020-2023  润新知