UI class in swift as struct


#1

Apple encourage the value type programming , then why UIKit element are not Struct. Why they are still class like UILable,UITableView etc ?


#2

Value types are encouraged for a number of reasons:

  • performance (compiler can make all kinds of assumptions for immutable types)
  • unintentional writing of shared memory (i.e. unexpected bugs)
  • concurrency / parallelism

That said, they have drawbacks. They don’t carry any sort of identity. Value semantics mean that 2 objects with the same values are equivalent.

But the same is not true with UIKit classes. This is a hierarchy of objects that have identity. 2 UIButtons that have the same properties are still 2 different instances, and they should be referred to by reference, not value.

Structs are not well suited towards modeling hierarchies that have circular references either. Think of view/superview… what would superview contain? A copy of the parent view?

A UIKit that is defined with value semantics would look very different than the UIKit we have today, and that is not necessarily a worthy endeavor. Not everything has to be a value type.