struct vs classes in swift

In Swift, both structs and classes are used to define custom data types. They share some similarities, but also have some differences in their behavior and usage.

One key difference between structs and classes is that structs are value types, while classes are reference types. This means that when you create an instance of a struct, a copy of that instance is made with its own unique memory space. On the other hand, when you create an instance of a class, it is passed by reference, and any changes made to the instance affect all references to that instance.

Classes are often used for creating objects that have behavior and state, and support concepts like inheritance, polymorphism, and encapsulation. Structs, on the other hand, are typically used for small, simple data structures that are immutable.

Here's an example of defining a class and a struct in Swift:

main.swift
// Defining a class
class MyClass {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

// Defining a struct
struct MyStruct {
    var name: String
    var age: Int
}
246 chars
17 lines

In general, you should use classes when you need to create objects with complex behavior and state, or when you need to take advantage of inheritance or polymorphism. For simpler data structures, or when mutability is not required, structs can often be a simpler and more efficient option.

gistlibby LogSnag