Swift - Structures



The structure is the most commonly used user-defined data type. It allows us to group the related data and operations into a single block. It is useful for encapsulating the data and the functionality into a single unit and provides more organized and readable code. In a structure, we can add functionality with the help of methods and properties.

In Swift, a structure does not require any extra file or interface for implementation, we can define a structure into a single file and the external interface accesses this code automatically. Structure is a value type.

Structure in Swift

Just like other programming languages in Swift, a structure is defined using a struct keyword along with a name and curly braces({}). Here the name must start with a capital letter such as School, not school. The curly braces contain all the properties and methods.

  • Properties − The constants and variables associated with the structure are known as the properties of the structure. They are commonly used to store and retrieve values in the instance of the structure. A structure can have multiple properties.

  • Methods − Functions associated with the structure are known as the methods of the structure. They are commonly used to define behaviour associated with the structure. Methods can have parameters and return values. A structure can have multiple methods. In Swift, using methods we are not allowed to change the properties. But if we want to change the properties inside the method, then we have to mark that method using a mutating keyword.

Syntax

Following is the syntax of the structure −

struct nameStruct { 
   // Properties
   Property 1 : Type
   Property 2 : Type

   // Methods
   func functionName(){
      // Statement
   } 
   
   // Mutating method
   mutating func functionName(){
      // Statement
   }
}

Example

In the following Swift example, we need to access the student's record containing marks for three subjects and find out the total of three subjects. So, we create a structure named markStruct with three marks as datatype 'Int'.

struct MarkStruct{
   var mark1: Int
   var mark2: Int
   var mark3: Int
}

Swift Structure Instance

A structure instance is an object that is created from the structure’s definition and represents some set of values for the properties. A single structure can have multiple instances and they are independent of each other, which means if we modify one instance that doesn't affect other instances.

We can create an instance of the structure by calling the structure initializer. A structure may or may not contain an initializer. So if a structure does not contain any initializer, then Swift will automatically receive a memberwise initializer to create a structure object. Using this initializer we can initialize each property by passing the initial value along with the name in the memberwise initializer.

Syntax

Following is the syntax of the structure instance −

var objectName = StructName(propertyName1: value, propertyName2: value)

Example

In the following Swift example, we will create an instance of MarkStruct.

struct MarkStruct{
   var mark1: Int
   var mark2: Int
   var mark3: Int
}

// Creating instance using memberwise initializer
var myObj = MarkStruct(mark1: 10, mark2: 20, mark3: 30)

We can also create a structure’s instance without providing parameters or initial values if the structure contains a default initializer.

struct MarkStruct{
   var mark1: Int
   var mark2: Int
   var mark3: Int

   // Default initialzer
   init(){
      Mark1  = 1
      Marks2 = 2
      Mark3 = 3
   }
}

// Creating instance using default initializer
var myInstance = MarkStruct()

Accessing the Properties of the Structure in Swift

To access the properties of the structure we can use a structure instance followed by a dot(.) and a property name. Using this notation we can also modify the values of the properties. With the help of this notation, we can also access and modify the sub-properties of the structure.

Syntax

Following is the syntax for accessing the properties of the structure −

structInstanceName.PropertyName

Following is the syntax for modifying the properties of the structure −

structInstanceName.PropertyName = value

Following is the syntax for accessing the sub-properties of the structure −

structInstanceName.PropertyName.subPropertyName

Following is the syntax for modifying the sub-properties of the structure −

structInstanceName.PropertyName.subPropertyName = value

Example

Swift program to access and modify the properties of the structure.

// Defining a structure
struct Employee {
   var name: String
   var age: Int
   var department: String
   var salary: Int
}

// Creating an instance of the Employee structure 
// with initial values of the properties
var emp = Employee(name: "Mona", age: 22, department: "HR", salary: 32000)

// Accessing the values of the properties using dot notation
print("Employee Details:")
print("Name: \(emp.name)")
print("Age: \(emp.age)")
print("Department: \(emp.department)")
print("Salary: \(emp.salary)")

// Modifying the values of the properties using dot notation
emp.age = 23
emp.salary = 33000

// Displaying the updated values
print("\nUpdated Values:")
print("Age: \(emp.age)")
print("Salary: \(emp.salary)")

Output

It will produce the following output −

Employee Details:
Name: Mona
Age: 22
Department: HR
Salary: 32000

Updated Values:
Age: 23
Salary: 33000

Example

Swift program to access and modify the sub-properties of the structure.

// Defining a structure with sub-properties
struct Address {
   var buildingName: String
   var city: String
   var pincode: String
}

// Defining a structure 
struct Student {
   var name: String
   var age: Int
   var address: Address
}

// Creating an instance of the Student structure 
// with initial values of the properties
var stud = Student(name: "Sumit", age: 22, address: Address(buildingName: "Anad Vihar", city: "Delhi", pincode: "333333"))

// Accessing the values of the properties and sub-properties using dot notation
print("Student Details:")
print("Name: \(stud.name)")
print("Age: \(stud.age)")
print("Building Name: \(stud.address.buildingName)")
print("City: \(stud.address.city)")
print("Pincode: \(stud.address.pincode)")

// Modifying the values of the sub-properties using dot notation
stud.address.buildingName = "Mohita Vihar"
stud.address.pincode = "333000"

// Displaying the updated values
print("\nUpdated Values:")
print("Building Name: \(stud.address.buildingName)")
print("Pincode: \(stud.address.pincode)")

Output

It will produce the following output −

Student Details:
Name: Sumit
Age: 22
Building Name: Anad Vihar
City: Delhi
Pincode: 333333

Updated Values:
Building Name: Mohita Vihar
Pincode: 333000

Accessing the Methods of the Structure in Swift

With the help of dot notation, we can also access the methods of the structure. Here also, we can use a structure instance followed by a dot(.) and a method name to access methods.

Syntax

Following is the syntax for accessing the method of the structure −

structInstanceName.methodName

Example

Swift program to access the methods of the structure.

// Defining a structure 
struct Parallelogram {
   var base: Double
   var height: Double

   // Method to calculate the area of the Parallelogram
   func calculateParallelogramArea() -> Double {
      return base * height
   }

   // Mutating method to resize the base and height of the Parallelogram 
   mutating func resizeParallelogram(by value: Double) {
      base += value
      height += value
   }
}

// Create an instance of the Parallelogram structure
var myObj = Parallelogram(base: 10.0, height: 9.0)

// Calling the calculateParallelogramArea() method
let area = myObj.calculateParallelogramArea()
print("Area of the Parallelogram: \(area)")

// Calling the mutating method i.e., resizeParallelogram()
myObj.resizeParallelogram(by: 3)

// Displaying the updated base and height of the Parallelogram
print("\nUpdated values: ")
print("Base: \(myObj.base)")
print("Height: \(myObj.height)")

Output

It will produce the following output −

Area of the Parallelogram: 90.0

Updated values: 
Base: 13.0
Height: 12.0

Structure as a Value Type in Swift

In Swift, structures are value type, which means that when we assign a structure to a variable or constant or can pass it to a function as a parameter, a copy of the structure is created. These copies are independent of the original instance, which means if we modify one copy of an instance that does not affect other copies of the structure’s instances.

Example

Swift program to demonstrate structure as a value type.

// Defining a structure 
struct Student {
   var name: String
   var age: Int
}

// Creating an instance of the Student structure 
var stud = Student(name: "Sumit", age: 22)

// Creating a copy of the stud instance
var details = stud

// Modifying the values of the properties
details.name = "Mohina"
details.age = 34

print("student 1: name-\(stud.name) and age-\(stud.age)")
print("student 2: name-\(details.name) and age-\(details.age)")

Output

It will produce the following output −

student 1: name-Sumit and age-22
student 2: name-Mohina and age-34

Structure with a self keyword in Swift

In a structure, the self keyword is used to distinguish between the property name and the method’s parameters. The self keyword is generally used with a property inside the methods or initializer so that the compiler can easily differentiate which one is a parameter and a property if their names are the same. Or the self keyword is used to refer to the current instance of the structure.

Syntax

Following is the syntax of self keyword −

self.PropertyName

Example

Swift program to demonstrate how to use self keyword in structure.

// Defining a structure 
struct markStruct{ 
   var mark1: Int
   var mark2: Int
   var mark3: Int
   
   // Initializer with same property and parameter name
   init(mark1: Int, mark2: Int, mark3: Int){
   
      // Using self keyword to distinguish between 
      // the property and parameter name
      // Here self.mark1 is the property name 
      self.mark1 = mark1
      self.mark2 = mark2
      self.mark3 = mark3
   }
}

// Creating an instance of the structure
var marks = markStruct(mark1: 98, mark2: 96, mark3:100)

// Displaying the values of the properties
print(marks.mark1)
print(marks.mark2)
print(marks.mark3)

Output

It will produce the following output −

98
96
100

Passing a Structure to a Function in Swift

In Swift, we are allowed to pass a structure into a function as a parameter by specifying a structure as a type of parameter. A structure is always passed in a structure by value, which means a copy of the structure will pass as a parameter and the modification does not affect the original structure. In a function, if we do not want to modify the structure, then we can pass it as a regular parameter, whereas if we want to modify the structure, then we have to pass it as an inout parameter.

Example

Swift program to demonstrate how to pass a structure to a function.

// Defining a structure 
struct Rectangle {
   var length: Double
   var width: Double
}

// Passing a structure to a function as a regular parameter
func areaOfRectangle(value:Rectangle){
   print("Area of the Rectangle is \(value.length * value.width)")
}

// Passing a structure to a function as an inout parameter
// Because we will modify the structure
func newAreaOfRectangle(data:inout Rectangle, byL newLength : Double, byW newWidth : Double){
   data.length *= newLength
   data.width *= newWidth
   print("New Area of the Rectangle is \(data.length * data.width)")
}

// Create an instance of the rectangle structure
var myObj = Rectangle(length: 10.0, width: 9.0)

// Calling the function
areaOfRectangle(value:myObj)

// Calling the another function 
newAreaOfRectangle(data: &myObj, byL : 2, byW : 3)

Output

It will produce the following output −

Area of the Rectangle is 90.0
New Area of the Rectangle is 540.0
Advertisements