Working with Structs in Swift: Basics and Benefits

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
May 30, 2024

Working with Structs in Swift

Structs in Swift are value types that allow you to encapsulate related properties and behaviors into a single unit. They are similar to classes but have some key differences such as value semantics and lack of inheritance.

Defining a Struct

To declare a struct in Swift, you use the struct keyword followed by the struct's name:

struct Person {
    var name: String
    var age: Int
}

Initializing a Struct

You can create an instance of a struct by using the initializer syntax:

let person1 = Person(name: "Alice", age: 30)
let person2 = Person(name: "Bob", age: 25)}

Accessing Properties

You can access the properties of a struct using dot notation:

print(person1.name) // Output: Alice
print(person2.age) // Output: 25}

Structs are Value Types

Unlike classes, which are reference types, structs are value types. This means that when you assign a struct instance to another variable or pass it as a function argument, a copy of the struct is created:

var person3 = person1
person3.name = "Eve"
print(person1.name) // Output: Alice
print(person3.name) // Output: Eve}

Methods in Structs

Structs can also have methods to perform operations on their properties:

struct Rectangle {
    var width: Int
    var height: Int
    
    func area() -> Int {
        return width * height
    }
}

let rectangle = Rectangle(width: 10, height: 5)
print(rectangle.area()) // Output: 50}