Understanding Structs

Structs are a way to define custom data types in Swift. Structs are similar to classes in that they allow you to create your own types with their own properties and methods. However, structs are value types, whereas classes are reference types. This means that structs are copied when they are assigned to a new variable or constant, whereas classes are not copied and are instead shared by reference.

Here's a simple example of a struct in Swift:

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

In this example, the Point struct defines a custom data type that represents a two-dimensional point on a coordinate plane. The Point struct has two properties, x and y, which represent the x and y coordinates of the point.

Once you define a struct, you can create variables or constants of that struct type, and you can access and modify the properties of those variables or constants. For example, you could create a point variable of the Point type and set its x and y coordinates like this:

var point = Point(x: 1.0, y: 2.0)
point.x = 3.0
point.y = 4.0

In this example, the point variable is created using the Point struct, and its x and y coordinates are set to 1.0 and 2.0, respectively. Then, the x and y coordinates of the point variable are modified to 3.0 and 4.0, respectively.

Structs are powerful and flexible. :)

Previous
Previous

Understanding Classes

Next
Next

Understanding Closures