Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift

How to create a struct in Swift

Ravi

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())
How struct in Swift works

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)
How dot notion can be used in swift

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()
Displaying the struct data by dot notion

Explanation

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

RELATED TAGS

swift
RELATED COURSES

View all Courses

Keep Exploring