Structures and Classes in Swift
Table of Contents
Difference between struct and class in swift : Struct is basically know as value type object where as class is called as reference type object.
Struct
Defining a Struct
struct School { var clothes: String var shoes: String }
Struct can be initialised as shown below
var stev = School(clothes: "Shirt", shoes: "puma") Accessing the member of Struct in Swift
stev.clothes stev.shoes
Classes
class School { var clothes: String var shoes: String }
class School { var clothes: String var shoes: String init(clothes: String, shoes: String) { self.clothes = clothes self.shoes = shoes } }
Accessing the properties of class
var rob = School(clothes: "Pants", shoes: "rebook") rob.clothes rob.shoes
- Ex. UIView, UIViewController
Struct Vs Class swift
Difference between struct and class in swift
Additional capabilities only available in class compare to struct in swift?
* Type Casting : We can check the type of the class in runtime.
* Reference Counting : Allow more than 1 reference to the class instance
* Inheritance : A class can inherit the property or characteristic of other class but in struct we cannot.
* De initialisation : we can de-initialise the class resource at any instant.
Memory Allocation of Struct and Class in swift
- Struct are allocated in Stack memory .
- Reference of the class object can be created on the Stack but the properties of the class object are store in the heap.