Logo
Swift Basics
Swift BasicsStructs and Classes

Structs and Classes

Structs and classes are two of the fundamental building blocks in Swift for creating complex data types. While they share many similarities, such as the ability to define properties and methods, they also have distinct differences. This section will help you understand when to use structs and when to use classes in your Swift projects.

What are Structs?

Structs are value types, which means they are copied when they are assigned to a new variable or passed to a function. They are best suited for defining simple types that encapsulate a few related data values.

Declaring Structs

You can declare a struct using the struct keyword.

struct Point {
    var x: Double
    var y: Double
}

Using Structs

Creating and using a struct is straightforward.

var point = Point(x: 0.0, y: 0.0)
point.x = 5.0
point.y = 10.0

What are Classes?

Unlike structs, classes are reference types. When you assign a class instance to a variable, both variables point to the same object in memory. Classes are more flexible than structs and are suitable for building complex data models.

Declaring Classes

Classes are declared using the class keyword.

class Circle {
    var radius: Double
    
    init(radius: Double) {
        self.radius = radius
    }
}

Using Classes

Creating and using a class involves instantiation using the init method.

let circle = Circle(radius: 5.0)

Key Differences

  1. Value vs Reference Types: Structs are value types, while classes are reference types.
  2. Inheritance: Classes can inherit from other classes, structs cannot.
  3. Type Casting: You can use type casting to check and interpret the type of a class instance at runtime.
  4. Deinitializers: Classes can have deinitializers to enable an instance to free up resources, structs do not have deinitializers.
  5. Mutability: Struct properties cannot be changed within its instance methods by default, whereas class properties can.

When to Use Structs and Classes?

  1. Use structs when:

    • You want a simple data structure that encapsulates a few related values.
    • You want the encapsulated values to be copied rather than referenced.
    • You don't need to inherit properties or methods from another existing type.
  2. Use classes when:

    • You want to create complex data models.
    • You want to share a mutable state across multiple parts of your app.
    • You want to take advantage of features like inheritance, type casting, and deinitializers.

Conclusion

Understanding the differences between structs and classes is crucial for effective Swift programming. While structs are excellent for creating simple, value-semantic types, classes provide more flexibility and functionality for building complex data models. Choose the appropriate type based on your specific needs to write efficient and maintainable Swift code.

Book a conversation with us for personalize training today!

Was this helpful?
Logo