Swift Structures

  Total Views : 190
  Comments : 0
  Keywords : Swift structures are the building blocks of our program code, Swift structures are value type the defined values copied when they are passed around in our code

Here we will learn structures in swift and how to use swift structures to construct building blocks of our programming code, create and access structure values, functions in structures, initializers in structures, how structures will behave as a value type, difference between structures and classes with examples. 

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 different type 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 as 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.

 

Following are the common things in both structures and classes in swift programming language.

 

  • Defining properties to hold values
  • Defining methods to implement 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 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 a structures in 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 swift programming language.

 

struct StructName {

// Variables

// Methods

// Properities

}

If you observe 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 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 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 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 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 above example in swift playground we will get 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 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 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 be remain same.

 

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

 

Rohini

Suresh

Key Points of Structure

Following are the some of 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 initialization level, it’s mandatory to initialize defined properties with values.

Difference between Classes and Structures

In swift, classes have some of additional capabilities when compared with structures. 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, compiler will throw an error.
  • Deinitializers not available in structures to free up assigned resources in 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 is having their own priorities so we need to consider following things to decide whether to use class or structure in swift programming language.

 

  • In swift if we want to share the mutable state between different parts of application then we need use a class. 
  • Structures are significantly faster, use less memory and useful for few simple data values.
  • In structures inheritance will not support so if we want 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. 

 

PREVIOUS

Swift Classes
 
 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User