Monday, December 5, 2016

Difference between class and struct in Swift!!!


Structures and classes in swift follow the same syntax for variable, constants and methods. And below are the common things in both class and struct.
  • Properties
  • Methods
  • Initializers to initialize values
  • Conform to protocols
And the main differences are
  • Class supports inheritance and structs not
  • Classes are reference types and structs are value types
Value Type:  When copying or assigning one value type variable to another value type variable, whole data will be copied and they are entirely two new objects. If any change in one object doesn't effect another object. Structures are value types.

//struct definition
struct Name{
    var first = "Pasumarthi"
    var last = "Chandra"
}

//struct variable initialization
var name = Name()

//copying name objet to anotherName object
var anotherName = name

//modifying
anotherName.last = "Chandra sekhar"

print("\(name.first) \(name.last)")
print("\(anotherName.first) \(anotherName.last)")


Result:
Pasumarthi Chandra
Pasumarthi Chandra sekhar

In the above swift code snippet, I have created structure object name and which is assigned to another structure object anotherName and modified anotherName property last, and displayed both name and anotherName objects and both displayed different values.

Reference Type: When copying or assigning one reference type variable to another reference type variable, both will be pointing to the same object and if any change in one object will effect the another object as both are pointing to the same reference. Classes are reference types.

//Class definition
class NameAsClass{
    var first = "Pasumarthi"
    var last = "Chandra"
}

//class initialization
var nameAsClass = NameAsClass()
//Copying one class object to another class object
var anotherNameAsClass = nameAsClass
//modifying 
anotherNameAsClass.last = "Chandra sekhar"
print("\(nameAsClass.first) \(nameAsClass.last)")
print("\(anotherNameAsClass.first) \(anotherNameAsClass.last)")

Result:
Pasumarthi Chandra sekhar
Pasumarthi Chandra sekhar

In the above swift code snippet, I have created class object nameAsClass and which is assigned to another class object anotherNameAsClass and modified anotherNameAsClass property last, and displayed both nameAsClass and anotherNameAsClass objects and both displayed same values.

References:
Click


Happy Coding!!!!



No comments:

Popular Posts