Search code examples
swiftstructreference-countingwwdc

Swift Struct's Reference Count


I have a question about struct

In WWDC2016, session recommend to use sturct (value type)

but if structs have 3 more inline variable words, struct must manage reference count as store large value to heap

then my question is
when struct have 3 another struct and each struct have 2 or 3 another struct or value type

I want to know how it works whether using reference Count or not in this situation

below is example of structs

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
}

Solution

  • Structures and enumerations have value-semantics. There is no notion of a reference count, because they are passed by copying. Their members may be pointers to reference-types, but the pointer itself is copied. As long as you don't have a reference-type in a structure, you don't need to worry about reference counting.

    Sure, one may argue that Swift internally uses copy-on-write optimizations using reference-types disguised as structures (eg. Array, Dictionary etc.), but they implement value-semantics.