Introduction to Swift

Apr 24 2024 · Swift 5.10, iOS 17, Xcode 15

Lesson 03: Classes & Structures

Memory Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

You’ve learned about initializers and the init function, which prepares the objects inside a struct or a class with their initial values. In this demo, you’ll learn about the deinit function for reference types which is responsible for the de-initialization of the object and cleaning it up when it’s being cleaned from memory. Only classes have a deinit; structs do not. Later in the demo, you’ll learn about the different sizes of data types and how much memory they allocate when you create instances from them.

class ExampleClass {

}
init() {
  print("Instance Created")
}
deinit {
  print("Instance Deleted")
}
do {
  print("Start Scope - 1")
}
print("End Scope - 1")
var variable1 = ExampleClass()
func getInstance() -> ExampleClass {
  print("getInstance() called")
  return ExampleClass()
}
do {
  print("Start Scope - 2")
  var variable1 = getInstance()
  print("Function call finished")
}
print("End Scope - 2")
do {
  print("Start Scope - 3")
  var variable1 = ExampleClass()
  do {
    print("Start Scope - 3 : Inner Scope - 1 \(variable1)")
    variable1 = ExampleClass()
  }
  print("End Scope - 3 : Inner Scope - 1")
}
print("End Scope - 3")
let boolValue = false
MemoryLayout.size(ofValue: boolValue)
let intValue: Int = 10
MemoryLayout.size(ofValue: intValue)

let floatValue: Float = 10
MemoryLayout.size(ofValue: floatValue)

let doubleValue: Double = 10
MemoryLayout.size(ofValue: doubleValue)
let int8Value: Int8 = 10
MemoryLayout.size(ofValue: int8Value)

let int16Value: Int16 = 10
MemoryLayout.size(ofValue: int16Value)

let int32Value: Int32 = 10
MemoryLayout.size(ofValue: int32Value)

let int64Value: Int64 = 10
MemoryLayout.size(ofValue: int64Value)
struct TwoIntsStruct {
  var intValue1: Int = 0
  var intValue2: Int = 0
}

struct FourIntsStruct {
  var intValue1: Int = 0
  var intValue2: Int = 0
  var intValue3: Int = 0
  var intValue4: Int = 0
}
MemoryLayout.size(ofValue: TwoIntsStruct())
MemoryLayout.size(ofValue: FourIntsStruct())
struct EmptyStruct {}

MemoryLayout.size(ofValue: EmptyStruct())
class TwoIntsClass {
  var intValue1: Int = 0
  var intValue2: Int = 0
}

class FourIntsClass {
  var intValue1: Int = 0
  var intValue2: Int = 0
  var intValue3: Int = 0
  var intValue4: Int = 0
}

MemoryLayout.size(ofValue: TwoIntsClass())
MemoryLayout.size(ofValue: FourIntsClass())
class EmptyClass {}
MemoryLayout.size(ofValue: EmptyClass())
See forum comments
Cinema mode Download course materials from Github
Previous: Memory Next: Conclusion