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 = hellohello.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=hello2hello2.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的属性也变了
总结以上是内存溢出为你收集整理的swift3新路程(9)结构体和类全部内容,希望文章能够帮你解决swift3新路程(9)结构体和类所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)