Swift Structures

In swift, structures are used to construct building blocks of our programming code and we can extend the functionality of structures by defining the different types of properties and methods.

 

In swift, we can define structures using struct keyword and define the properties, methods in structures same as constants, variables, and functions.

 

In swift structures are quite similar to classes to group similar information together based on our requirements. One of the main difference is structures are value types and classes are reference types.

 

The following are the common things in both structures and classes in a swift programming language.

 

  • Defining properties to hold values
  • Defining methods to implement the required functionality
  • Defining initializers
  • Defining type methods
  • Defining subscripts, Protocols, Extensions

In swift, structures are always copied when they are passed around in our code because when we assign the same structure to multiple variables and if we modify one, only that value alone will change, not others because each new variable was a copy of the original, not a reference.

 

Unlike other programming languages, we don’t need to create any separate interface or implementation files for structures. In swift when we create structures in a single file, automatically that class file will be available for other code blocks to use that functionality in applications.

Syntax of Swift Structures

Generally, in swift structures are defined by using struct keyword. Following is the syntax of defining structures in a swift programming language.

 

struct StructName {

// Variables

// Methods

// Properities

}

If you observe the above syntax we defined structure by using struct keyword along with structure name and we defined a required properties, variables and functions in structures based on our requirements in swift programming language.

Swift Define a Structure

Following is the example of defining or declaring structure in swift programming language.

 

struct ClassRoom {

var TeacherName : String

var StudentName : String

var MonitorName : String

var StudentMarks: Int

}

If you observe above example we defined a structure called “ClassRoom” using struct keyword and we defined multiple properties as a string or integer variables inside of structure.

Swift Structure Instances

Generally, in swift we can access structure properties, variables and methods by creating structure instance like as shown below.

 

Swift Structure Instance with Defined Properties

 

Following is the example of creating instance for newly created structure in swift programming language.

 

struct ClassRoom {

var TeacherName : String

var StudentName : String

var MonitorName : String

var StudentMarks: Int

}

var sd = ClassRoom()

If you observe above example we created instance for ClassRoom by using that we can access the properties of structure based on our requirements.

Swift Assign and Access Structure Properties

Following is the example of assigning and accessing property values from a structure based on our requirements.

 

struct ClassRoom {

var TeacherName: String

var StudentName: String

var MonitorName: String

var StudentMarks: Int

}

var studentdetail = ClassRoom(TeacherName: "Rohini Alavala", StudentName: "Suresh Dasari", MonitorName: "Praveen Kumar", StudentMarks:80)

print("Teacher: \(studentdetail.TeacherName)")

print("Student: \(studentdetail.StudentName)")

print("Monitor: \(studentdetail.MonitorName)")

print("Marks: \(studentdetail.StudentMarks)")

If you observe above example we created an instance for structure “ClassRoom” and assigned same to the variable “studentdetail”. In structure instance we assigned values to the properties and accessing those structure properties using variable name.

 

When we run above code in swift playground we will get result like as shown below

 

Teacher: Rohini Alavala

Student: Suresh Dasari

Monitor: Praveen Kumar

Marks: 80

In swift we have another way of assigning values to structure properties. Following is example of assigning and accessing structure properties in swift programming language.

 

struct ClassRoom {

var TeacherName : String = ""

var StudentName : String = ""

var MonitorName : String = ""

var StudentMarks: Int = 0

}

var studentInfo = ClassRoom()

studentInfo.TeacherName = "Rohini Alavala"

studentInfo.StudentName = "Suresh Dasari"

studentInfo.MonitorName = "Praveen Kumar"

studentInfo.StudentMarks = 80

 

print("Teacher: \(studentInfo.TeacherName)")

print("Student: \(studentInfo.StudentName)")

print("Monitor: \(studentInfo.MonitorName)")

print("Marks: \(studentInfo.StudentMarks)")

If you observe above example we defined structure (ClassRoom) properties with initial values and we created instance for that structure and assigned same to a variable “studentdetail”. We are assigning values to structure properties by using variable name.

 

When we run the above code in swift playground we will get result like as shown below

 

Teacher: Rohini Alavala

Student: Suresh Dasari

Monitor: Praveen Kumar

Marks: 80

This is how we can define and assign values to structure properties in a swift programming language.

Swift Functions in Structures

In swift structures we can define functions along with properties based on our requirements.

 

Following is the example of defining and using functions in swift structures.

 

struct ClassRoom {

var TeacherName : String = ""

var StudentName : String = ""

var MonitorName : String = ""

var StudentMarks: Int = 0

 

func Details() -> String {

return ("Teacher: \(TeacherName), Student: \(StudentName), Monitor: \(MonitorName), Marks: \(StudentMarks)")

}

}

var studentInfo = ClassRoom()

studentInfo.TeacherName = "Rohini"

studentInfo.StudentName = "Suresh"

studentInfo.MonitorName = "Praveen"

studentInfo.StudentMarks = 80

print(studentInfo.Details())

If you observe above example we defined function (“Details”) in structure (ClassRoom) and showing details from the function by using structure instance variable.

 

When we run the above example in swift playground we will get a result like as shown below

 

Teacher: Rohini, Student: Suresh, Monitor: Praveen, Marks: 80

This is how we can use functions in swift structures based on our requirements.

Swift Initializers for Structures

Generally in swift structures, initializers are used to assign initial values to the properties defined in structure during initialization of structure instances and we can customize the initialization of an instance by implementing an initializer.

 

Following is the example of using initializers in swift structures.

 

struct ClassRoom {

var TeacherName : String

var StudentName : String

var MonitorName : String

var StudentMarks: Int

 

init(TeacherName: String,StudentName: String,MonitorName: String,StudentMarks: Int) {

self.TeacherName = TeacherName

self.StudentName = StudentName

self.MonitorName = MonitorName

self.StudentMarks = StudentMarks

}

}

var sd = ClassRoom(TeacherName: "Rohini", StudentName: "Suresh", MonitorName: "Praveen", StudentMarks: 80)

print("Teacher: \(sd.TeacherName), Student: \(sd.StudentName), Monitor: \(sd.MonitorName), Marks: \(sd.StudentMarks)")

If you observe above example we defined structure “ClassRoom” with different type of properties to hold values based on our requirements and we defined a custom initializer “init()” to accept multiple arguments.

 

In initializer we used self keyword it refers the instance that’s being initialized and we used self keyword to access arguments to avoid ambiguity with local parameters. Once the copy of structures members are created with initializer we are passing values to structure instance.

 

When we run the above program in swift playground we will get result like as shown below

 

Teacher: Rohini, Student: Suresh, Monitor: Praveen, Marks: 80

To know more about using initializers in a swift programming language, check this Swift initializers.

Swift Structures are a Value Type

In swift, structures are the value type so the property values will always copy when we assign to another variable and the original value will remain same and does not affect the original value of variable.

 

Following is the example of showing how structures are values types in swift programming language.

 

struct UserDetails {

var name : String = ""

}

var userInfo = UserDetails(name: "Rohini")

var info2 = userInfo

info2.name = "Suresh"

print(info2.name)

print(userInfo.name)

If you observe above example we defined structure (UserDetails) and created instance for the structure and assigned to a variable “userInfo”. After that again we created new variable “info2” and assigned previously created variable “userInfo” to new variable.

 

Initially we updated name in variable “userInfo” and once we assign variable “userInfo” to “info2” again we updated name value but the value of variable “info2” will not affect “userInfo” value because structures are value types so when we pass value to variable the original value of variable will remain same.

 

When we run the above program in swift playground we will get a result like as shown below

 

Rohini

Suresh

Key Points of Structure

The following are some of the important points which we need to remember while using structures in our swift programming language.

 

  • Structures are the value type when we pass its value to variable the original value of variable will be remain same.
  • By using Dot Syntax, we can access all the name types (properties, methods) which we declared in structure.
  • Structures have default initializer but we also set the custom initializer.
  • At the initialization level, it’s mandatory to initialize defined properties with values.

Difference between Classes and Structures

In swift, classes have some of the additional capabilities when compared with structures. The following are the differences between classes and structures in swift programming language.

 

  • No inheritance in Structures. It’s not possible for us to Inherit from other types.
  • Classes use type-casting in swift to define a class as a superclass or subclass but type-casting not available for structures.
  • By default no mutation available for structure methods. In case if we try to change the value of property, the compiler will throw an error.
  • Deinitializers not available in structures to free up assigned resources in an instance.
  • Not possible for us to create multiple references to the same instance in Structures.

Choose Between Classes and Structures

In swift, both structures and classes are having their own priorities so we need to consider the following things to decide whether to use class or structure in a swift programming language.

 

  • In swift, if we want to share the mutable state between different parts of the application then we need to use a class. 
  • Structures are significantly faster, use less memory and useful for few simple data values.
  • In structures, the inheritance will not support so if we want to implement inheritance functionality we need to go for classes.
  • The properties defined in structures are value types so the values will be copied rather than referenced when we pass around an instance of the structure.
  • In structures, we don’t need to inherit properties from another existing type.

By considering above mentioned points you can decide which one is better to use in your swift applications based on your requirements.