what is difference between struct and class

Generated on 7/30/2024

1 search

In Swift, the primary difference between structs and classes lies in their storage and semantics:

  1. Storage:

    • Structs use inline storage. This means that the data for a struct is stored directly in the variable that holds it. When you copy a struct, you copy all of its data.
    • Classes use out of line storage. This means that the data for a class is stored separately, and the variable holds a reference (pointer) to that data. When you copy a class, you copy the reference, not the actual data.
  2. Semantics:

    • Structs have value semantics. When you copy a struct, you get a completely independent copy of the data. Changes to one copy do not affect the other.
    • Classes have reference semantics. When you copy a class, you get another reference to the same data. Changes to the data through one reference are visible through all references.
  3. Performance Implications:

    • Structs avoid heap allocation and can be more efficient for small data types because they are stored inline. However, copying large structs can be costly because all data is duplicated.
    • Classes can be more efficient for large data types because they avoid copying the data itself, only the reference. However, they involve heap allocation and reference counting, which can introduce overhead.
  4. Use Cases:

    • Use structs when you need value semantics, such as for small, immutable data types or when you want to ensure that copies are independent.
    • Use classes when you need reference semantics, such as for shared, mutable state or when you need to use inheritance.

For more detailed information, you can refer to the following sessions from WWDC:

Relevant Sessions

  1. Explore Swift performance
  2. A Swift Tour: Explore Swift’s features and design
  3. Consume noncopyable types in Swift