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

本文通过示例对比了Swift中结构体与类在传递方式上的核心差异:结构体按值传递,而类按引用传递。展示了属性变化如何影响各自的实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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的属性也变了



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值