Wednesday, June 19, 2019

Difference between struct and class in swift

In Swift, similar to C++, struct instance is created on stack, and class instance is created on heap. When assigning a struct variable to another, a new struct instance is created and all properties are copied. When assigning a class variable to another, the two variable points to the same class instance. === and !== can be used to check whether two variable refer to the same class instance

Struct method cannot change its property unless mutating is specified.
Class method can change its property.

Struct variable defined with let, its properties cannot be changed by assigning to different value
Class variable defined with let,  its properties can be assigned to different value.

Struct cannot inherit from base struct, only protocol and extension are available for struct
Class can inherit from base class.


Note similar types in swift and objective C can have different behavior. For example, Array in swift is struct type, but NSArray in objective c is class type. So when assigning a swift Array variable to a different variable, a new array object is created. On the contrary, when assigning a Objective C NSArray variable to a different variable, two variables points to the same instance and === operator will return true.

Actually operator === cannot be used to compare Swift struct variables, as they always point to different instance.

No comments:

Post a Comment