Open In App

Swift Structures

Last Updated : 05 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A structure is a general-purpose building block of any code and stores variables of different data types under a single unit. Just like other programming languages in Swift you can also define the properties and methods into a structure, where the properties are the set of constants or variables that are stored as part of the structure. Also, there is no need to create any separate interface to implement the structure, you can define the structure in a single file and then the external interface will automatically use the structure. 

In Swift, a structure is a value type. Value type means a type whose value is copied whenever it is assigned to a variable or a constant or passed to a function, so we can say that whenever an instance of the structure is created and any value types that the properties have can be copied whenever they are passed in the code and whenever we define a new structure then that means we define a new data type. We can use structure to encapsulate simple data values, and also can copy the encapsulated data and the related properties by their values, not by the reference. Using structure we can also create our own types which have their own methods and properties. We can simply create a structure using the struct keyword. 

Syntax:

struct nameOfStructure{

// structure properties and methods

}

Example: 

Swift




// Swift program to illustrate how to create a structure
import Swift
 
// Creating structure
// Using struct keyword
struct geeksforgeeks{
 
    // Properties of the Structure
    var employeeName = "Mohit"
    var employeeID = 1234
    var employeeDepartment = "HR"
    var joiningYear = 2019
}


Structure Instance

Just like a class in Swift, we can also create an instance of the structure, and using this instance we can access the properties and methods of the structure. The structure also uses initializer syntax to create an instance. It is the easiest and most efficient way to create an instance of the structure. You need to simply write the name of the structure followed by empty parentheses, for example, geeksforgeeks(). Using a single instance, we can access all the properties and methods of a structure along with their values and a single structure can contain multiple instances.

Syntax:

let instanceName = StructureName()

Example:

Swift




// Swift program to illustrate how to create an instance of the structure
import Swift
 
// Creating structure
// Using struct keyword
struct geeksforgeeks{
    var employeeName = "Mohit"
    var employeeID = 1234
    var employeeDepartment = "HR"
    var joiningYear = 2019
}
 
// Creating the instance of geeksforgeeks structure
var myinstance = geeksforgeeks()


Accessing the Structure Properties

We can access the properties of the structure using the instance of the structure followed by a dot and the name of the property. Also using this syntax we can access the sub-properties of the structure. This syntax is also used to assign value to the specified property or to the sub-property.

Syntax:

// For accessing property

instanceName.PropertyName

// For accessing sub-property

instanceName.PropertyName.subPropertyName

// For assigning value to the property 

instanceName.PropertyName  = 23

Example:

Swift




// Swift program to illustrate how to access the properties of a structure
import Swift
 
// Creating structure
// Using struct keyword
struct geeksforgeeks{
    var employeeName = "Mohit"
    var employeeID = 1234
    var employeeDepartment = "HR"
    var joiningYear = 2019
}
 
// Creating the instance of geeksforgeeks structure
var myinstance = geeksforgeeks()
 
// Accessing the properties of geeksforgeeks structure
print("Employee Name:", myinstance.employeeName)
print("Joining Year:", myinstance.joiningYear)


Output:

Employee Name: Mohit
Joining Year: 2019

Memberwise Initializers

Structure always generates a memberwise initializer automatically, it is also known as the default initializer. So without wasting time, you can easily use these memberwise initializers to initialize the properties of a new structure instance. Or we can say if the property of the structure is not initialized with any initial value then using memberwise initializers we can initialize the property with the initial value. And we can also use memberwise initializers if the property contains the initial value.

Syntax:

let varName = structureName(propertyName1: Value, propertyName2: Value) 

Example:

Swift




// Swift program to illustrate memberwise initializers
import Swift
 
// Creating structure
// Using struct keyword
struct geeksforgeeks{
   
    // Properties of the structure
    var employeeName = "Mohit"
    var employeeID = 1234
    var employeeDepartment = "HR"
    var joiningYear = 2019
}
 
// Creating the instance of geeksforgeeks structure
var myinstance = geeksforgeeks()
 
// Accessing the properties of geeksforgeeks structure
print("Employee Id before updating:", myinstance.employeeID)
 
// Memberwise Initializers
// Here we change the value of employeeID property
// to a new value using Memberwise Initializers
var newdata = geeksforgeeks(employeeID: 234)
print("Employee Id after updating:", newdata.employeeID)
print("________________________________")
 
// Creating another structure
struct employeeDetail{
    var age : Int
    var contact : Int
}
 
// Creating the instance of employeeDetail structure
// Here age and contact properties doesnot contain
// any initial value. So we initialize this property
// using Memberwise Initializers
var empinstance = employeeDetail(age: 24, contact: 7777777777)
 
// Accessing the property
print("Employee Age: ", empinstance.age)
print("Employee Contact: ", empinstance.contact)


Output:

Employee Id before updating: 1234
Employee Id after updating: 234
________________________________
Employee Age:  24
Employee Contact:  77777777

Function Inside Structure

A structure can also contain functions. When a function is defined inside a structure then that function is called a method. The method can use the properties of the structure. To access the function we can use the dot syntax. As shown in the below example, where we created an increment() method in the geeksforgeeks structure to find the increment in the salary of the employee and then access that method using dot syntax. 

Syntax:

struct nameOfStructure{

func functionName(){

// Function Body

}

}

In Swift, you are generally not allowed to write methods that change the properties, but you can specially request them. If you want to change the property present inside the method then you need to declare that function using the mutating keyword.

Syntax:

struct nameOfStructure{

mutating func functionName(){

// Function Body

}

}

Example:

Swift




// Swift program to illustrate method in structure
import Swift
 
// Creating structure
// Using struct keyword
struct geeksforgeeks{
   
    // Property
    var salary = 230000
     
    // Method
    func increment(){
     
        // Finding the new salary
        let newsalary = 2 * salary
        print("New salary: ", newsalary)
    }
}
 
// Creating the instance of geeksforgeeks structure
var myinstance = geeksforgeeks()
 
// Accessing the method
myinstance.increment()


Output:

New salary:  460000

Using self in the structure

Sometimes in a structure, the name of the method parameter is the same as the property, so the compiler does not get the right context that you want to operate on the property or on the method parameter. So to overcome this kind of situation we use the self keyword. We generally use the self keyword with the property because the parameter name automatically takes higher precedence. Using the self keyword the compiler can easily distinguish between the name of the parameter and property. When we are working with the self keyword which means we are explicitly accessing the current value of the named type, it is exactly equal to the instance itself, so you are allowed to use the self property to refer to the current object within its own object method. Self keyword is generally useful in initializers, when two variables of the same name are present in the same scope and you want to assign a new value to the property, not to the parameter, in that case, you can use the self keyword before the property name using dot syntax.

Syntax:

self.propertyName

Example:

Swift




// Swift program to illustrate self keyword
import Swift
 
// Creating structure
// Using struct keyword
struct geeksforgeeks{
   
    // Property
    var article = 230
     
    // Method
    func update(article: Int = 23){
     
        // Finding the updated data
        let updatedData1 = article + 234
        print("Updated Data 1: ", updatedData1)
         
        // Finding the updated data
        // Using self keyword
        let updatedData2 = self.article + 234
        print("Updated Data 2: ", updatedData2)
    }
}
 
// Creating the instance of geeksforgeeks structure
var myinstance = geeksforgeeks()
 
// Accessing the method
myinstance.update()


Output:

Updated Data 1:  257
Updated Data 2:  464


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads