Monday 14 November 2016

Class vs Struct In Swift

Today we learn about class and structure used in swift.Classes and structures are general-purpose, flexible constructs that become the building blocks of your program’s code. 
You define properties and methods to add functionality to your classes and structures by using exactly the same syntax as for constants, variables, and functions.

Similarities In Class Vs Structure 
  1. Define properties to store values.
  2. Define methods to provide functionality
  3. Define subscripts to provide access to their values using subscript syntax
  4. Define initializers to set up their initial state
  5. Be extended to expand their functionality beyond a default implementation
  6. Conform to protocols to provide standard functionality of a certain kind
Difference between Class and Structure
  1. Inheritance enables one class to inherit the characteristics of another.
  2. Type casting enables you to check and interpret the type of a class instance at runtime.
  3. Deinitializers enable an instance of a class to free up any resources it has assigned.
  4. Reference counting allows more than one reference to a class instance.
  5. Classes are reference type while Structure are value type.
Note*
Structure are value type and they don't use  referencing counting.

Syntax of Class and Structure

  1. class SomeClass {
  2. // to do
  3. }
  4. struct SomeStructure {
  5. // to do
  6. }
  7. Value Type Vs Reference Type: 
      A Value Type holds the data within its own memory allocation and a Reference Type contains a pointer to another memory location that holds the real data. Reference Type variables are stored in the heap while Value Type variables are stored in the stack.
      All structures and enumerations are value types in Swift. This means that any structure and enumeration instances you create—and any value types they have as properties—are always copied when they are passed around in your code.
        Assignment and Copy Behavior for  Strings, Arrays, and Dictionaries:
        In Swift, many basic data types such as String, Array, and Dictionary are implemented as structures. This means that data such as strings, arrays, and dictionaries are copied when they are assigned to a new constant or variable, or when they are passed to a function or method.
        This behavior is different from Foundation: NSString, NSArray, and NSDictionary are implemented as classes, not structures. Strings, arrays, and dictionaries in Foundation are always assigned and passed around as a reference to an existing instance, rather than as a copy.

        Example Of Value Type And Reference Type


          class Address{
            var fullAddress:String
            var pincode: String
            init(fullAddress:String,pincode:String) {
              self.fullAddress = fullAddress
              self.pincode = pincode
            }
          }
          class Person {
            var name: String
            var address:Address
            init(name:String,address:Address) {
              self.name = name
              self.address = address
            }
          }
          var address = Address(fullAddress: "House # 98 ,Street # 3,Sector 50,Mumbai", pincode: "123456")
          let peter = Person(name: "Peter", address: address)
          let john = Person(name: "johan", address: address)
          print("Peter Address->",peter.address.fullAddress)
          print("John Address->",john.address.fullAddress)
          //Now johan moved to another location
          john.address.fullAddress = "House # 80, Sector 47 ,New Delhi"
          print("Now John Address->",john.address.fullAddress)
          print("Now Peter Address Also->",peter.address.fullAddress)

          Output:

          Peter Address-> House # 98 ,Street # 3,Sector 50,Mumbai
          John Address-> House # 98 ,Street # 3,Sector 50,Mumbai
          Now John Address-> House # 80, Sector 47 ,New Delhi
          Now Peter Address Also-> House # 80, Sector 47 ,New Delhi

          Here you can  see that Peter address is also updated due to reference type behaviour of class.

          How to solve this problem now?????? To solve this problem you have to use structure here because structure are value type.

            Convert  Address type to struct instead of class. 

                struct Address{
                  var fullAddress:String
                  var pincode: String
                  init(fullAddress:String,pincode:String) {
                    self.fullAddress = fullAddress
                    self.pincode = pincode
                  }
                }
                class Person {
                  var name: String
                  var address:Address
                  init(name:String,address:Address) {
                    self.name = name
                    self.address = address
                  }
                }
                var address = Address(fullAddress: "House # 98 ,Street # 3,Sector 50,Mumbai", pincode: "123456")
                let peter = Person(name: "Peter", address: address)
                let john = Person(name: "johan", address: address)
                print("Peter Address->",peter.address.fullAddress)
                print("John Address->",john.address.fullAddress)
                //Now johan moved to another location
                john.address.fullAddress = "House # 80, Sector 47 ,New Delhi"
                print("Now John Address->",john.address.fullAddress)
                print("Now Peter Address Also->",peter.address.fullAddress)

                Output :

                Peter Address-> House # 98 ,Street # 3,Sector 50,Mumbai
                John Address-> House # 98 ,Street # 3,Sector 50,Mumbai
                Now John Address-> House # 80, Sector 47 ,New Delhi
                Now Peter Address Also-> House # 98 ,Street # 3,Sector 50,Mumbai

                Now you see that Peter address is not updated because we make address as struct type.
                    Conclusion:
                             Today we learn about classes and structure
                              If you have any questions just leave a comment below and I’ll respond as soon as I can.

No comments:

Post a Comment