Swift Structs.

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

by The Captain

on
May 21, 2023

Understanding the Basics of Structs in Swift

Structs are one of the most basic constructs in the Swift programming language. These are value types that allow you to group related data and logic together, making it easy to work with complex data models. In this tutorial, we will dive into the basics of structs in Swift, and also explore some of their unique features. Creating a Struct in Swift Creating a struct is very similar to creating a class in Swift. Here is an example to create a `Person` struct:
struct Person {
    var name: String
    var age: Int
}
In the code above, we define a `Person` struct with two properties, `name` and `age`. Structs are Value Types One of the key differences between classes and structs is that structs are value types. This means that when you pass a struct to another function or variable, it is copied. Let's take a look at an example:
struct Person {
    var name: String
    var age: Int
}

var person1 = Person(name: "John", age: 25)
var person2 = person1

print(person1.age) //Output: 25
print(person2.age) //Output: 25

person1.age = 30
print(person1.age) //Output: 30
print(person2.age) //Output: 25}
In the above code, we create a `Person` struct, `person1`, with name "John" and age 25. We then assign `person1` to `person2`. When we change the age of `person1`, it doesn't affect `person2` because structs are copied by value. Mutability in Structs When you create a struct in Swift, all its properties are mutable by default. However, if you want to create a constant struct, you can use the `let` keyword to declare it as a constant. Let's look at an example:
struct Circle {
    let radius: Double
    
    var area: Double {
        return Double.pi * radius * radius
    }
}

let circle = Circle(radius: 5)
print(circle.area) //Output: 78.53981633974483

// This line would give a compile-time error because circle is a constant struct
// circle.radius = 10}
In the code above, we define a `Circle` struct with a `radius` property. We also add an `area` property that calculates and returns the area of the circle. Since we declare the `Circle` struct as a constant using `let`, we cannot change the `radius` property after initialization. Summary In summary, structs are a fundamental construct in Swift that allows you to group related data and logic together. They are value types that are copied when passed around. Structs can also be declared as constants using the `let` keyword. Understanding struct basics can help you build more complex data models in your Swift code.