Class vs Struct

Overview

Value Type vs Reference Type

Value Type: Each instance keeps a unique copy of data in memory (Logan Koskenka).

Reference Type: Each instance shares a single copy of data (Logan Koshenka).

Value Types:

  • Structures

  • Enumarations

  • Strings

  • Integers

  • Dictionaries

  • Arrays

Reference Types

  • Classes

  • Closures

  • Functions

The functionality of class over a struct

  • It will inherit properties and results from the other class and add to it. It means if you want to use tha data in other views you should use Class, but if you don't want to than use Struct.

  • Inheritance

    • Copies of structs are always unique, whereas copies of classes actually point to the same shared data (HWS).

    • The technical term for this distinction is “value types vs reference types.” Structs are value types, which means they hold simple values such as the number 5 or the string “hello”. It doesn’t matter how many properties or methods your struct has, it’s still considered one simple value like a number. On the other hand, classes are reference types, which means they refer to a value somewhere else. (HWS)

Class inherits the property but Struct does not

Struct
struct User {
    var username = "Anonymous"
}

var user1 = User()
var user2 = user1
user2.username = "Taylor"

print(user1.username) // print: "Anonymous"
print(user2.username) // print: "Taylor"
Class
class User {
    var username = "Anonymous"
}

var user1 = User()
var user2 = user1
user2.username = "Taylor"

print(user1.username) // print: "Taylor"
print(user2.username) // print: "Taylor"

Sources

Videos

Articles / Documents

Last updated