STRUCTS

最后更新于:2022-04-01 04:44:32

## STRUCTS Structs(结构体) 是一种复杂数据类型,包含了多个值,通过 struct 关键字定义一个结构体: ~~~ struct Person { var clothes: String var shoes: String } ~~~ Swift 让你非常简单地创建一个结构体变量,只需要将初始值传入即可: ~~~ let taylor = Person(clothes: "T-shirt", shoes: "sneakers") let other = Person(clothes: "short skirts, shoes: "high heels") ~~~ 通过结构体变量名以及属性名来访问属性的值: ~~~ print(taylor.clothes) print(other.shoes) ~~~ Swift 有一个名为"copy on write"的机制,当你将一个结构体变量赋给另一个变量时,会独立拷贝一份: ~~~ struct Person { var clothes: String var shoes: String } let taylor = Person(clothes: "T-shirts", shoes: "sneakers") let other = Person(clothes: "short skirts", shoes: "high heels") var taylorCopy = taylor taylorCopy.shoes = "flip flops" taylor //(clothes: "short skirts", shoes: "high heels") taylorCopy //(clothes: "short skirts", shoes: "flip flops") ~~~
';