【Xcode/Swift】Difference between Class and Struct

Swift is a powerful programming language used for developing iOS, macOS, and watchOS applications. One of the fundamental concepts of Swift is the ability to define custom data types. Two of these custom data types are class and struct, and in this post, we will explore the differences between them.

Classes and structs are similar in that they both allow you to define custom data types, but they differ in how they handle memory allocation, inheritance, and mutability.

Memory Allocation

Classes are reference types, which means that they are allocated in memory on the heap, and their instances are passed around by reference. When you create a new instance of a class, a reference to that instance is returned. This reference points to the actual object in memory, and any changes made to the object are reflected in all references to that object.

Structs, on the other hand, are value types, which means that they are allocated in memory on the stack, and their instances are passed around by value. When you create a new instance of a struct, a copy of that instance is made, and any changes made to the copy do not affect the original.

Inheritance

Classes in Swift support inheritance, which means that you can create a new class based on an existing class. The new class inherits all the properties and methods of the existing class, and you can also add new properties and methods to the new class.

Structs, on the other hand, do not support inheritance. You cannot create a new struct based on an existing struct.

Mutability

Classes in Swift are mutable, which means that you can change the properties of a class instance after it has been created. For example, you can change the value of a property or add a new property to an existing instance.

Structs in Swift are immutable by default, which means that you cannot change the properties of a struct instance after it has been created. To make a struct mutable, you need to declare it as a variable using the “var” keyword.

Simple App Example

To illustrate the differences between classes and structs, let’s create a simple app that calculates the area of a rectangle.

class Rectangle {
    var width: Int
    var height: Int
    
    init(width: Int, height: Int) {
        self.width = width
        self.height = height
    }
    
    func calculateArea() -> Int {
        return width * height
    }
}

struct StructRectangle {
    var width: Int
    var height: Int
    
    func calculateArea() -> Int {
        return width * height
    }
}

var rectangle = Rectangle(width: 10, height: 20)
var structRectangle = StructRectangle(width: 10, height: 20)

// Change the width of the rectangle
rectangle.width = 15

// Try to change the width of the structRectangle (won't work)
// structRectangle.width = 15

// Print the area of the rectangle and the structRectangle
print(rectangle.calculateArea()) // Output: 300
print(structRectangle.calculateArea()) // Output: 200

In this example, we created a class called Rectangle and a struct called StructRectangle. Both of these have a width and a height property and a method to calculate the area of the rectangle.

We created an instance of each and set their width and height properties. We then changed the width of the rectangle instance to 15, and we tried to change the width of the structRectangle instance, which did not work.

Finally, we printed the area of each instance, which showed that the rectangle has an area of 300 (10 x 15), while the structRectangle has an area of 200 (10 x 20).

Conclusion

Classes and structs in Swift are both useful in different situations. If you need to create a custom data type that can be subclassed, has reference semantics, or needs to be mutable, then a class may be the best choice. On the other hand, if you need a lightweight data type that has value semantics and is immutable by default, then a struct may be more appropriate.

In general, you should prefer to use a struct over a class unless you have a specific need for reference semantics or subclassing. Structs can also offer performance advantages in certain situations since they are allocated on the stack rather than the heap.

When working with structs, it’s important to remember that they are passed by value, so if you pass a struct to a function or method, a copy of the struct is made. This can be inefficient if the struct is large, so you may want to consider passing a reference to the struct instead.

In conclusion, understanding the differences between classes and structs in Swift is essential for creating efficient and effective code. By choosing the appropriate type for your data, you can ensure that your code is both performant and maintainable.

この記事は役に立ちましたか?

はい
いいえ
貴重なフィードバックありがとうございます!