Swift 结构的引用计数

Swift Struct's Reference Count

我有一个关于结构的问题

WWDC2016中session推荐使用sturct(值类型)

但如果结构有 3 个以上的内联变量字,结构必须管理引用计数以将大值存储到堆

那么我的问题是
当结构有 3 个另一个结构并且每个结构有 2 或 3 个另一个结构或值类型时

我想知道在这种情况下是否使用引用计数是如何工作的

下面是结构的例子

struct ViewModel {
     var titleModel: TitleModel
     var contentModel: ContentModel
     var layoutModel: LayoutModel
}

struct TitleModel {
     var text: String
     var width: Float
     var height: Float
}

struct ContentModel {
     var content: String
     var width: Float
     var height: Float
}

struct LayoutModel {
     var constant: Float
     var multiply: Float
}

结构和枚举具有值语义。没有引用计数的概念,因为它们是通过复制传递的。它们的成员可能是指向引用类型的指针,但指针本身是被复制的。只要结构中没有引用类型,就无需担心引用计数。

当然,有人可能会争辩说 Swift 在内部使用写时复制优化,使用伪装成结构的引用类型(例如 ArrayDictionary 等),但是他们实施 值语义。

查看结构的这些大小。

print(sizeof(ViewModel))     //->72 == sizeof(TitleModel) + sizeof(ContentModel) + sizeof(LayoutModel)
print(sizeof(TitleModel))    //->32 == sizeof(String) + sizeof(Float) + sizeof(Float)
print(sizeof(ContentModel))  //->32 == sizeof(String) + sizeof(Float) + sizeof(Float)
print(sizeof(String))        //->24 (a mystery...)
print(sizeof(LayoutModel))   //->8 == sizeof(Float) + sizeof(Float)

(sizeof(String)好像是"mystery",但那又是另外一个问题。)

Swift 没有给我们任何关于结构中成员分配的保证, 但是,就目前而言,Swift 以 "flat and natural".

的方式分配所有成员
 ViewModel:
 offset content                 size
  0     TitleModel.text          24
 24     TitleModel.width          4
 28     TitleModel.heigth         4
 32     ContentModel.content     24
 56     ContentModel.width        4
 60     ContentModel.height       4
 64     LayoutModel.constant      4
 68     LayoutModel.multiply      4
 --
 72     Total(=sizeof(ViewModel))

您的 ViewModel 不包含对其成员的引用。它只是将其成员平放在里面。没有引用,所以没有引用计数。

您可能对结构实际包含一些引用时如何管理它们有疑问。但这与您的 when struct have 3 another struct and each struct have 2 or 3 another struct or value type.

不同