Skip to main content

What is the difference between class and structure in Swift?

 

The Main difference in Class and Structure 

        Classes are reference types. Structures are value types. Classes have an inheritance that allows one class to inherit the characteristics of another. Structures do not support inheritance.


Class ( Reference Types )

  • Reference Type
    • When you copy a reference type, each instance shares the data. The reference itself is copied, but not the data it references. When you change one, the other changes too.
  • Inheritance
    • Classes have an inheritance that allows one class to inherit the characteristics of another.
  • Initializer
    • We have to define the initializer manually.
  • Storage
    • Class instances are stored on the heap.
  • Thread Safe
    • Classes are not fully threadsafe.


Example : 

 
class EmployeeList {
    
    var name: String
    var age: Int
    
    init(name: String, age: Int) {
        self.name = name
        self.grade = grade
    }
}

let emp1 = EmployeeList(name: "Dixit Akabari", age: 27)
let emp2 = emp1
emp2.name = "Ms Dhoni"

print("emp1 name: \(emp1.name)")
print("emp2 name: \(emp2.name)")

OutPut :

    emp1 name: Ms Dhoni
    emp2 name: Ms Dhoni


Structure ( Value types )

  • Reference Type
    • When you copy a value type each instance keeps a unique copy of the data. If you change one instance, the other doesn’t change too.
  • Inheritance
    • Classes have an inheritance that allows one class to inherit the characteristics of another.
  • Initializer
    • We have to define the initializer manually.
  • Storage
    • Class instances are stored on the heap.
  • Thread Safe
    • Classes are not fully threadsafe.


Example : 


struct EmployeeListStruct {
   var name: String
   var age: Int
}

let emp1 = EmployeeListStruct(name: "Dixit Akabari", age: 8)
var emp2 = emp1
emp2.name = "MS Dhoni"

print("Employee1 name: \(emp1.name)")
print("Employee2 name: \(emp2.name)")

OutPut :

    Employee1 name: Dixit Akabari
    Employee2 name: MS Dhoni


Conclusion

        Now Hopefully, you’ll be easier to reason about choosing between a class or a struct.


Comments

Popular posts from this blog

Create APIManager Class Using Alamofire Swift

Create APIManage.Swift File. // //    APIManager.swift // //    Created by Dixit Akabari on 7/1/20. //    Copyright © 2020 Dixit Akabari. All rights reserved. // import  UIKit import  Alamofire open   class   APIManager :  NSObject  {           // =========== POST API Calling ===========           public   class   func   callPostAPI (param: [ String :  Any ], URlName:  String , controller:  UIViewController , withblock: @escaping  ( _  response:  AnyObject ?)-> Void ){                           //check internet connection available or not          if  ( AppDelegate . getAppDelegate (). connected ()) {                                        let  url =  "Base_Url"   +  URlName                           //API headers              var  _headers :  HTTPHeaders  = [ "Content-Type" : "application/x-www-form-urlencoded" ]              _headers[ "Authorization" ] =  "token"   // pass api token here if need                           AF . sess

Record UIView In iOS Swift (XCode)

This blog used for helping to Record a UIView.                     It records animations and actions as they happen by taking screen shots of a UIView in a series and then creating a video and saving it to your app’s document folder.  Create  Recorder.swift  File .      This file take screenshot of UIView in a series and save that images in document directory.   import UIKit @objc public class Recorder : NSObject {          var displayLink : CADisplayLink ?     var outputPath : NSString ?     var referenceDate : NSDate ?     var imageCounter = 0          public var view : UIView ?     public var name = "image"     public var outputJPG = false          var imagesArray = [ URL ]()          public func start () {                  if ( view == nil ) {             NSException (name: NSExceptionName (rawValue: "No view set" ), reason: "You must set a view before calling start." , userInfo: nil ). raise ()         }         else {