Swift Struct With Examples

In this tutorial, we’ll be discussing an important building block in Swift, namely Structures. Swift struct keyword is used to create structures in swift programming.

Swift Struct

On a high level, Structures are custom data types that let us store data in the form of properties and functions. One of the highlights of Structures is that they are value types and not reference types.
Let’s look at the basic syntax of a struct.


struct Name {
  // properties here
}

A Structure is defined using the keyword struct followed by the name and curly braces.

Properties are normal variables/constants that are defined in a struct. We’ll look more into Properties in a later tutorial.

Unlike other languages, Struct in Swift is fully featured. They allow properties, functions, initializers, protocols etc. Unlike Classes, Structs in Swift doesn’t support inheritance.

Let’s open up the playground and play around with structures in it.

Swift Struct Example

Here’s an example of a Struct definition with properties.


struct Rectangle {
    var width = 0
    var height = 0
}

An instance of the above struct can be created in the following way.


var rectangle = Rectangle()

To access or modify the properties of a structure we use the dot operator on the instance as shown below.


print(rectangle.width) // prints 0
print(rectangle.height) //prints 0
rectangle.width = 10
rectangle.height = 10

If the instance was initialized as let, changing the properties won’t be possible.


let rectangle = Rectangle()
rectangle.width = 10 //compile-time error
rectangle.height = 10 //compile-time error

Defining functions inside a Structure


struct Rectangle {
    var width = 0
    var height = 0
    func area(width :Int, height: Int) -> String
    {
         return "Area is  (width*height)"
    }
}

Calling the function using an instance of the structure as shown below:


var rectangle = Rectangle()
rectangle.width = 10
rectangle.height = 10
rectangle.area(width: rectangle.width, height: rectangle.height) //prints 100

Modifying struct properties inside functions

To modify a property inside a function we need to mark the function with the keyword mutating.


struct Rectangle {
    var width = 0
    var height = 0
    mutating func printModifiedWidth() -> String
    {
        width = width*2
        return "Modified width is (width)"
    }
}
var rectangle = Rectangle()
rectangle.width = 10
rectangle.printModifiedWidth() //prints "Modified width is 20"

Note: Properties inside a structure can’t be changed inside a simple function.
Declaring function as mutating inside struct allows us to alter properties in Structures.

Swift Struct Initialisers

Default initializer takes 2 forms. Either an empty initializer() or the memberwise initializer that lists the structure’s properties inside its parenthesis so that you can assign new values to them.

A memberwise initializer for the above structure would look as follows:


var rectangle = Rectangle(width: 10, height: 10)

A custom initialiser can be defined as follows:


struct Rectangle {
    var width = 0
    var height = 0
    init(width: Int, height: Int) {
        self.width = width*2
        self.height = height*2
    }
}
var rectangle = Rectangle(width: 10, height: 10)
print(rectangle.width) //prints 20
print(rectangle.height) //prints 20

Initialisers Delegation is also possible as shown below.


struct Rectangle {
    var width = 0
    var height = 0
    init(width: Int, height: Int) {
        self.width = width
        self.height = height
    }
    init(width: Int) {
    self.init(width: width, height: width)
    }
}
var square = Rectangle(width: 10)
print(square.width) //prints 10
print(square.height) //prints 10

Swift Struct Static Functions

Static Functions can be called without creating an instance of Structure as shown below:


struct Rectangle {
    var width = 0
    var height = 0
    static func printString() -> String
    {
    return "Hello how you're doing"
    }
}
Rectangle.printString() //prints "Hello how you're doing"

Swift Struct Computed Properties

Properties can be computed dynamically using the following syntax.


struct Rectangle {
    var width = 0
    var height = 0
    var area: Int {
        get {
            return width*height
        }
        set {
            area = 0
        }
    }
}

set is used to give an initial value to the property.
get is the one that actually returns the computed property.
Using the computed properties the area property would be automatically calculated when the width or height is altered.


var rectangle = Rectangle()
print(rectangle.area) //prints 0
rectangle.width = 20
rectangle.height = 20
print(rectangle.area) //prints 400

Swift Structures are passed by values and not by reference


struct Rectangle {
    var width = 0
    var height = 0
    var area: Int {
        get {
            return width*height
        }
        set {
            area = 0
        }
    }
}
var rectangle = Rectangle()
print(rectangle.area)
rectangle.width = 20
rectangle.height = 20
var rect = rectangle
rect.width = 30
print(rectangle.width) //prints 20 and NOT 30

This brings an end to swift struct tutorial. We’ll be discussing Classes in our next Swift Tutorial.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: