加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift3新路程(9)结构体和类

发布时间:2020-12-14 06:43:19 所属栏目:百科 来源:网络整理
导读:Use struct to create a structure. Structures support many of the same behaviors as classes,including methods and initializers. One of the most important differences between structures and classes is that structures are always copied when t

Use struct to create a structure. Structures support many of the same behaviors as classes,including methods and initializers. One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code,but classes are passed by reference.

上面这句话是官方文档的

我们可以看到结构的一些形式和类是基本相似的

但是他们有一个很大的区别就是,结构体是值引用,类的是址引用,可能这么说不太直观

我写了个例子,我们可以看一下

struct Hello {
    var firstName:String
    var secondName:String
    func sayHello() -> Void {
        print("Hello (firstName) (secondName)")
    }
}

var hello = Hello(firstName: "Liu",secondName: "Mingchuan")
var hello_1 = hello

hello.sayHello()
hello.secondName = "Ryoma"
hello.sayHello()

hello_1.sayHello()

class Hello2 {
    var firstName:String = ""
    var secondName:String = ""
    
    func sayHello() -> Void {
        print("Hello (firstName) (secondName)")
    }
}
var hello2 = Hello2()
var hello2_1=hello2

hello2.firstName = "Liu"
hello2.secondName = "Mingchuan"
hello2.sayHello()
hello2.secondName = "Ryoma"
hello2.sayHello()
输出

Hello Liu Mingchuan

Hello Liu Ryoma

Hello Liu Mingchuan


Hello Liu Mingchuan

Hello Liu Ryoma

Hello Liu Ryoma


我们就可以看到结构体的hello改变属性之后,hello_1的属性并没有改变

而类的就不同了,当hello2的属性变调之后,hello2_1的属性也变了

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读