摘自苹果书籍 “结构和类之间最重要的区别之一是,结构在代码中传递时总是被复制,但类是通过引用传递的。”

有人能帮我理解一下这是什么意思吗?对我来说,类和结构似乎是一样的。


当前回答

正如许多人已经指出复制结构体和类的区别一样,这可以从它们在c语言中的来源来理解,像这样的结构体

struct A {
    let a: Int
    let c: Bool
}

在func父对象或结构体的局部内存中,它将是这样的

64bit for int
8 bytes for bool

现在

class A {
    let a: Int
    let c: Bool
}

而不是存储在本地内存或结构或类中的数据内容,它将是一个单一指针

64bit address of class A instance

当你复制这两个时,很容易看出为什么会有区别,复制第一个,你复制了64位的int和8位的bool,复制第二个,你复制了64位的地址到A类的实例,你可以有同一个内存地址的多个副本,都指向同一个实例,但结构体的每个副本都将是它自己的副本。

现在事情变得复杂了因为你可以把这两个混合起来

struct A {
    let a: ClassA
    let c: Bool
}

你的记忆会是这样的

64bit address of class A instance
8 bytes for bool

This is a problem because even though you have multiple copies of the struct in your program, they all have a copy to the same object ClassA, this means just like multiples reference to instance ClassA you pass around have to have a reference count kept of how many reference to the object exists to know when to delete them, you program can have multiple references to struct A that need to keep a reference count to their ClassA instances, this can be time consuming if your struct has a lot of classes in them, or the structs it contains has lots of classes in them, now when you copy your struct, the compiler has to generate code that goes through every single class instance referenced in your struct and substructs, and increment there reference count to keep track of how many references there are. This can make classes much faster to pass around as you just need to copy its single address, and it won't need to increase the reference count of any of its children because it want reduce the reference count of any child it contains until its own reference count reaches 0.

The thing gets even more complicated with some Apple struct types, that they actually have object types in them, the good thing about data that is reference to, is it can be stored in memory and be lengthened and contractor at will and they can be very large, unlike data stored on local stack, so types like String, Array, Set, Dictionary though they act like struct and will even make a duplicate of there internal data if you try to modify them so you don't change all occurrence, there data still has to be reference counted and so a struct containing a lots of these types can still be slow, because the internal data for each one has to be retained.

当然,传递结构类型可以减少大量错误的可能性,但它们也会降低程序的速度,这取决于所包含的类型。

其他回答

下面是一个类的例子。请注意,当名称更改时,两个变量引用的实例将如何更新。鲍勃现在是苏了,所有提到鲍勃的地方都是这样。

class SomeClass {
    var name: String
    init(name: String) {
        self.name = name
    }
}

var aClass = SomeClass(name: "Bob")
var bClass = aClass // aClass and bClass now reference the same instance!
bClass.name = "Sue"

println(aClass.name) // "Sue"
println(bClass.name) // "Sue"

现在使用结构体,我们看到值被复制,每个变量保留自己的值集。当我们将名称设置为Sue时,aStruct中的Bob结构体不会被更改。

struct SomeStruct {
    var name: String
    init(name: String) {
        self.name = name
    }
}

var aStruct = SomeStruct(name: "Bob")
var bStruct = aStruct // aStruct and bStruct are two structs with the same value!
bStruct.name = "Sue"

println(aStruct.name) // "Bob"
println(bStruct.name) // "Sue"

所以对于表示有状态的复杂实体来说,类是非常棒的。但是对于仅仅是测量值或相关数据位的值,结构体更有意义,这样您可以轻松地复制它们并使用它们计算或修改值,而不用担心副作用。

Usually (in most programming languages), objects are blocks of data that are stored on heap, and then a reference (normally a pointer) to these blocks, contains a name is using to access these blocks of data. This mechanism allows sharing objects in the heap by copying the value of their references (pointers). This is not the case of basic data types such as Integers, and that is because the memory needed to create a reference is almost the same as the object (in this case integer value). Thus, they will be passed as values not as a reference in the case of large objects.

Swift使用struct来提高String和Array对象的性能。

这是一本很好的读物

斯威夫特类型

命名类型或标称类型或有名称的类型 复合类型或非名义类型或没有名称的类型

值类型是一种类型,其值在赋值给变量或常量、传递给函数或从函数返回时被复制。(as and is检查构造的副本)

当引用类型被赋值给变量或常量,或者被传递给函数时,引用类型不会被复制

值类型:

Struct, Enum[About],元组 struct String, struct Array(Set, Dictionary)

(objective - c int…)

字符串,内置集合值类型包含对堆的内部引用,以管理它的大小

当您分配或传递值类型时,将创建数据的新副本。copy on write - COW机制用于某些特定的类(如Collections(Array, Dictionary, Set))[About],并进行了一些优化,例如在修改对象时创建副本。对于自定义类型,您应该自己支持COW 当你修改一个实例时,它只在局部起作用。 如果Value为局部变量,则使用堆栈内存[关于]

引用类型: 类,函数

(Objective-C所有其他)

使用ARC

当你分配或传递引用类型时,一个新的引用将被创建到原始实例(实例的地址被复制)。 当您修改一个实例时,它会产生全局影响,因为该实例可以被指向它的任何引用共享和访问。 通常使用堆内存[大约]

建议默认为“type”。Value类型的最大优点是它们通常是线程安全的

参考类型

它们可以遗传, 可以使用Deinit (), 通过引用===比较实例, Objective-C互操作性,因为值类型是在Swift中引入的。

[堆栈vs堆] [let vs var, class vs struct] [类别vs结构]

在结构和类之间选择 类型 类和结构

这个问题似乎是重复的,但无论如何,下面的问题将回答大多数用例:

One of the most important differences between structures and classes is that structures are value types and are always copied when they are passed around in your code, and classes are reference type and are passed by reference. Also, classes have Inheritance which allows one class to inherit the characteristics of another. Struct properties are stored on Stack and Class instances are stored on Heap hence, sometimes the stack is drastically faster than a class. Struct gets a default initializer automatically whereas in Class, we have to initialize. Struct is thread safe or singleton at any point of time.

而且, 要总结结构和类之间的区别,有必要了解值类型和引用类型之间的区别。

在复制值类型时,它将从其中复制所有数据 你要复制到新变量中的东西。它们是分开的 事物和改变一个并不影响另一个。 复制引用类型时,新变量引用 与你要复制的东西相同的内存位置。这意味着 改变一个会改变另一个因为它们都指向 相同的内存位置。 下面的示例代码可以作为参考。

/ / sampleplayground.playground

  class MyClass {
        var myName: String
        init(myName: String){
            self.myName = myName;
        }
    }

    var myClassExistingName = MyClass(myName: "DILIP")
    var myClassNewName = myClassExistingName
    myClassNewName.myName = "John"


    print("Current Name: ",myClassExistingName.myName)
    print("Modified Name", myClassNewName.myName)

    print("*************************")

    struct myStruct {
        var programmeType: String
        init(programmeType: String){
            self.programmeType = programmeType
        }
    }

    var myStructExistingValue = myStruct(programmeType: "Animation")
    var myStructNewValue = myStructExistingValue
    myStructNewValue.programmeType = "Thriller"

    print("myStructExistingValue: ", myStructExistingValue.programmeType)
    print("myStructNewValue: ", myStructNewValue.programmeType)

输出:

Current Name:  John
Modified Name John
*************************
myStructExistingValue:  Animation
myStructNewValue:  Thriller

下面是一个例子,它精确地显示了struct和class之间的区别。

在操场上写的代码的截图

struct Radio1{
    var name:String
    //    init(name:String) {
    //        self.name = name
    //    }
}

struct Car1{
    var radio:Radio1?
    var model:String

}

var i1 = Car1(radio: Radio1(name:"murphy"),model:"sedan")
var i2 = i1
//since car instance i1 is a struct and 
//this car has every member as struct ,
//all values are copied into i2

i2.radio?.name //murphy
i2.radio = Radio1(name: "alpha")
i2.radio?.name //alpha

i1.radio?.name //murphy

//since Radio1 was struct , 
//values were copied and thus
// changing name  of instance of Radio1 in i2 
//did not bring change in i1

class Radio2{
    var name:String
    init(name:String) {
        self.name = name
    }
}

struct Car2{
    var radio:Radio2?
    var model:String

}
var i3 = Car2(radio: Radio2(name:"murphy"),model:"sedan")
//var radioInstance = Radio2(name: "murphy")
//var i3 = Car2(radio: radioInstance,model:"sedan")

var i4 = i3
//since i3 is instance of struct
//everything is copied to i4 including reference of instance of Radio2
//because Radio2 is a class



i4.radio?.name //murphy
i4.radio?.name="alpha"
i4.radio?.name //alpha

i3.radio?.name //alpha

//since Radio2 was class, 
//reference was copied and 
//thus changing name of instance 
//of Radio2 in i4 did  bring change in i3 too


//i4.radio?.name
//i4.radio = Radio2(name: "alpha")
//i4.radio?.name
//
//i3.radio?.name