24. Structures in Swift

Structures are classes look a like. You can create a Person class like this

class PersonClass {
    
    // properties
    var name : String = ""
    var age  : Int = 0
    
    // method
    func getInfo() -> String{
        
        return ("My name is \(name) and my age is \(age)")
    }
}

If you want to create a structure of Person just replace the word ‘class’ with ‘struct’

struct PersonStruct {
    
    // properties
    var name : String = ""
    var age  : Int = 0
    
    // method
    func getInfo() -> String{
        
        return ("My name is \(name) and my age is \(age)")
    }
}

and your structure is ready to use. Structures can have variables and methods exactaly same like class. You can access them same like class. Check this example :

// Class object declaration
var pc = PersonClass()
pc.name = "Khan"
pc.age = 30

// Structure variable declaration
var ps = PersonStruct()
ps.name = "Khan"
ps.age = 30

There is no difference between classes and structures, But few

Difference between Class and Structure

  1. Structures cannot inherit other structures.
  2. Structures do not have deinitializers.
  3. Structures have built in initializer.
  4. Structures can have only one reference to one instance.

First two points are quite straight forward. There is no inheritance in structures and there is no deinitializer method available in structures. Lets discuss point 3 and 4 in detail.

Built in initializers
In previous articles about classes, you have seen in detail that Swift is very strict with member initialization. You must assign some values when variables is declared or provide init() for variable initialization.

class PersonClass {
    
    // properties
    var name : String
    var age  : Int

    init(personname :String , personage:Int){
        name = personname
        age = personage
    }
}

But Structures on the other hand are very relaxed. You don’t need to assign values to variables within structure’s body  or to create any initializer method. Following structure is correct and Swift compiler will not throw any error.

struct PersonStruct {
    
    // properties
    var name : String
    var age  : Int
}

When you are creating structure variable, you can assign values at the same time because Swift provides built-in init method for structures.

var ps = PersonStruct(name: "Khan", age: 30)

 

Structures cannot have multiple references
For understand this point, create two functions. One function will take PersonClass as a parameter

func iAmTenYearsOlder(var p : PersonClass) {

    p.age = p.age + 10
}

and second function will take PersonStructure as a parameter

func iAmTenYearsOlder(var p : PersonStruct) {

    p.age = p.age + 10
}

Now Create a PersonClass object and assign “Khan” to name and 30 to age. After variable initialization, call iAmTenYearsOlder() method and pass PersonClass object pc to it.

var pc = PersonClass()

pc.name = "Khan"
pc.age = 30

iAmTenYearsOlder(pc)
pc.age

iAmTenYearsOlder() will add 10 in current age. Now pc.age has value 40. Lets do exact same thing with Structure PersonStructure.

var ps = PersonStruct(name: "Khan", age: 30)

ps.age

iAmTenYearsOlder(ps)

ps.age

Now structure member variables are initialized, name = Khan and age = 30. Call iAmTenYearsOlder() method and pass PersonStructure variable ps to it.  iAmTenYearsOlder() will add 10 in current age. But notice that when you will check ps.age, the value of age will not change. ps.age has same old value which is 30.

When you pass structure as a parameter to function, you create an independent copy of a structure not a reference to structure. When you add 10 in structure’s age, it does not effect the original structure. But when you pass object as a parameter you pass reference to that object not a copy, so when you add 10 in class’s age, you change the original one. This is the difference between pass by value and pass by reference.

Check this simple code, which help you to understand the difference between reference and copy

    // Pass by Reference
    var pcobj1 = PersonClass()
    pcobj1.name = "Khan"
    pcobj1.age = 25

    // Create new object by assiging pcobj1
    var pcobj2 = pcobj1

    //  check pcobj2.age value
    pcobj2.age

    // Update pcobj1 by assiging pcobj1.age = 50
    pcobj1.age = 50

    // Check pcobj2 is also updated, because pcobj2 is a 
    // reference to pcobj1 not an independent copy
    pcobj2.age


    // Pass by Copy
    var psstruct1 = PersonStruct(name: "Khan", age: 30)
    psstruct1.age

    // create psstruct2 by assigining psstruct1
    var psstruct2 = psstruct1

    // update psstruct1.age
    psstruct1.age = 60    
    
    //but notice that there is no effect on psstruct2.age 
    // because both are independent copies
   
    psstruct2.age

 

 

Download file from GitHub