Swift Class versus Structure

In Swift Just like classes play a important role , Structure do play a important role.

What could be the notable difference?
First one is Structure is pass by value and Classes are pass by reference.  Below is a simple example to understand the meaning of it.



func getAddress(_ object: Any)->String{
    var newObject = object
    var address:String = String("Could Not CalculateAddress")
    withUnsafePointer(to: &newObject) {
        
        address = "\($0)"
    }
    return address
}

func getAddressForClass(_ object:AnyObject) -> Any {
    return Unmanaged<AnyObject>.passUnretained(object).toOpaque()
}

//Structure
struct User{
    var name:String
    var userId:Int
}

func changeStructuredValue(_ inputStruct:User){
    var newInputStruct = inputStruct
    newInputStruct.name =  "Rose"
    print("Modifying Struct , Address Location= \(getAddress(newInputStruct))")
}

var structUser = User(name: "John", userId: 1)
print("Original Structure = \(structUser) Address Location= \(getAddress(structUser))")
changeStructuredValue(structUser)
print("Modified Structure = \(structUser) Address Location= \(getAddress(structUser))")

print("\n\n")


///Class
class Person {
    var personName : String?
    var personId   : Int?
}

func changeClassValue(_ inputPerson: Person){
    inputPerson.personName = "Eddie"
    print("Modifying Class Address Location= \(getAddressForClass(inputPerson))")
}

var person = Person()
person.personName = "ED"
person.personId = 189
print("Original Class = \(person.personName) Address Location= \(getAddressForClass(person))")
changeClassValue(person)

print("Modified Class = \(person.personName) Address Location= \(getAddressForClass(person))")




-------The output of the above code would be--------------

Original Structure = User(name: "John", userId: 1) Address Location= 0x00007fff5f2af048
Modifying Struct , Address Location= 0x00007fff5f2aef58
Modified Structure = User(name: "John", userId: 1) Address Location= 0x00007fff5f2af048



Original Class = Optional("ED") Address Location= 0x0000618000072500
Modifying Class Address Location= 0x0000618000072500

Modified Class = Optional("Eddie") Address Location= 0x0000618000072500

You might have noticed , changeStructuredValue does change the value and is local to the scope. It creates a new copy for the function changeStructuredValue.

On the other side for the class the address remains the same before and after the modifying the value.

This was small example , that could help understanding this concept. Please write in your comments for any further feedback.


Comments

Popular posts from this blog

hitTest on iOS to identify the view being hit

CMTimeMakeWithSeconds explained

How to set Custom Section Header in UITableView for ios sdk version greater than 6