Small bites of knowledge for Swift and CS
A Struct is an object in Swift that provides a single reference. Structs behave like a custom data type, providing a container for holding information in the form of constants and variables. Unlike classes Structs are Value Types. This means that only the single instance has knowledge of the information contained within it. Another way to think about this is that when they are passed around their data is copied instead of referenced, so each instance of a struct is unique. Structs can contain enums, functions, or even classes and other structs, and can be initialized as both mutable and immutable instances. Probably the greatest benefit of Structs is that they are not reference types, meaning they are independent and safe from reference mutations (a reference mutation happens when thing A causes changes to thing B, and all of the other things that know about things B see those changes).
Some appropriate uses for Structs:
- data objects
- data models
- data copy objects (think NSManagedObject to Unmanaged copy for use in a view)
Get new content delivered directly to your inbox.