How to create a struct in Swift

Overview

A struct in Swift is a data structure that can hold variables of different data types. It can also have functions defined in it.

Syntax

struct structName{

// variables
// functions

}

Example

struct Student {
var name = ""
var age = 0
}
print(Student())

A structure called Student that consists of name and age as variables is created.

Access the variables of the structure

Structures are just a blueprint. To use any structure as such, we need to create an instance/object of the structure.

We can access the individual variables of a structure using the dot . notation. The variables can be accessed using the objects/instances created from the structure.

Example

struct Student {
var name = ""
var age = 0
}
var student = Student()
student.name = "john"
student.age = 23
print(Student())
print(student.name)
print(student.age)

Explanation

  • Line 7: We create an instance of the Student struct.
  • Line 8–9: We set the name and age variables of the structure using the . notation.

Functions in a structure

A structure can also have functions defined in them. To invoke those functions, we use the . notation.

Example

struct Student {
var name = ""
var age = 0
func display(){
print("Student[name=\(name),age=\(age)]")
}
}
var student = Student()
student.name = "john"
student.age = 23
student.display()

Explanation

  • Line 14: We invoke the display() function using the . notation.