Swift-Tips之'==='与'=='的区别

栏目: Swift · 发布时间: 6年前

内容简介:如果Student类不实现
  • == :它默认比较基本类型的值,比如:Int,String等,它不可以比较引用类型(reference type)或值类型(value type),除非该类实现了 Equatable
let str1 = "hello"
let str2 = "hello"
//true
print(str1 == str2)
复制代码
  • === :它是检查两个对象是否完全一致(它会检测对象的指针是否指向同一地址),它只能比较引用类型(reference type),不可以比较基本类型和值类型(type value)

如果Student类不实现 Equatable 协议的话,它是不支持 == 运算符的

class Student: Equatable {
    var name = ""
    init(name: String) {
        self.name = name
    }
    
    static func == (lhs: Student, rhs: Student) -> Bool {
        return lhs.name == rhs.name
    }
}

let stu1 = Student(name: "rose")
let stu2 = Student(name: "rose")
let stu3 = stu1
//true
print(stu1 == stu2)
//true
print(stu1 === stu3)
//false
print(stu1 === stu2)
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Code Reading

Code Reading

Diomidis Spinellis / Addison-Wesley Professional / 2003-06-06 / USD 64.99

This book is a unique and essential reference that focuses upon the reading and comprehension of existing software code. While code reading is an important task faced by the vast majority of students,......一起来看看 《Code Reading》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试