Structure ,Class,Enum,CaseIterable in Swift

Varun Singhal
2 min readSep 26, 2020

Struct are value type whereas classes are reference type.It simply means when we copy struct their is two unique copy of data .whereas when we copy of classes there is two reference of single data.

Structure store values, not addresses ,never restore on return .arrays, structures, strings are a Example

Classes pass address and access to formal is indirect reference to actual

Structure is value based so they are stored in Stack.Whereas Class has reference type they stored on heap.So Struct does not support Inheritance , Polymorphism whereas class support both.All member of class by default is private whereas struct member are public in nature.Classes allow garbage collection because garbage collection work on heap.Object of class are deallocated when instance are not being used by other code.Struct has no Garbage collector.So In Terms of Memory classes has more efficient then Structure.

Size of Empty class is 1 Bytes whereas empty struct size is of 0 Bytes.

Here is Example:

class News {

let title : String

let url : URL

var readcount : Int = 0

init(title: String, url: URL) {

self.title = title

self.url = url

}

}

struct NewsStruct {

let title : String

let url : URL

var readcount : Int = 0

}

let newsClass = News(title: “Struct vs Class”, url: URL(string: “www.xyz.com")!)

let newsClassCopy = newsClass

newsClassCopy.readcount = 10

print(newsClassCopy.readcount) // Give result 10

let newsStruct = NewsStruct(title: “Struct vs Class”, url: URL(string: “www.xyz.com")!)

let newsStructCopy = newsStruct

newsStructCopy.readcount = 10

print(newsStructCopy.readcount) // Give result 0

Struct are value type so its value can’t modified within instance method by default.In order to modified its property we have to use mutating keyword in the instance method.

Enum is user defined data which consist of set of related value.

enum SomeEnumeration {

// enumeration definition goes here

}

Swift enumeration cases don’t have an integer value set by default, unlike languages like C and Objective-C.

Case Iterable When using CaseIterable type you can access all type collection of case byusing all case property.

  1. enum Beverage: CaseIterable {
  2. case coffee, tea, juice
  3. }
  4. let numberOfChoices = Beverage.allCases.count

--

--