Object Oriented Programming III
Class vs Struct
Object Oriented Programming III
Class vs Struct
0
0
Checkbox to mark video as read
Mark as read

Class

We've only seen struct types of objects so far, but we can use class as well. If we declare a class we can see the first difference: if there is any not assigned variable, then you need to implement an init for it.

class Person {
    var fullName: String
    
    init(fullName: String) {
        self.fullName = fullName
    }
}

But there are more differences that are important to understand, actually, one of the most common questions on iOS developer interviews is "What's the difference between a class and an struct?.

Class vs Struct

The main difference between class and struct is that the first one is a reference type, and the second one is a value type. But, what does this mean? Let's explore this in an example.

First I'll define a class, I'll create two instances, myPerson and myPersonCopy, then when I change the name of the myPersonCopy it will also change myPerson name, because it keeps a reference, due to they are in the same memory address.

class Person {
    var fullName: String
    
    init(fullName: String) {
        self.fullName = fullName
    }
}

var myPerson = Person(fullName: "Pablo")
var myPersonCopy = myPerson

myPersonCopy.fullName = "Andrea"

print(myPerson.fullName)

However, this is not the case if we use a struct.

struct Person {
    var fullName: String
}

var myPerson = Person(fullName: "Pablo")
var myPersonCopy = myPerson

myPersonCopy.fullName = "Andrea"

print(myPerson.fullName)

When we use a struct, myPersonCopy is actually a copy of myPerson, any change on myPersonCopy won't affect to myPerson. They are in different memory addresses.

When should I used then?

In general we'll use struct to declare our objects, specially for models and views. However, since struct cannot mutate theirselfs (not in a safe way), for these cases we will use class.

course

Quiz Time!

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy