# 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](https://www.hackingwithswift.com/quick-start/understanding-swift/why-does-swift-have-both-classes-and-structs)).
  * 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&#x20;*****reference*****&#x20;types**, which means they refer to a value somewhere else. ([HWS](https://www.hackingwithswift.com/quick-start/understanding-swift/why-do-copies-of-a-class-share-their-data))

### Class inherits the property but Struct does not

{% code title="Struct" %}

```swift
struct User {
    var username = "Anonymous"
}

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

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

{% endcode %}

{% code title="Class" %}

```swift
class User {
    var username = "Anonymous"
}

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

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

{% endcode %}

## Sources

### Videos

{% embed url="<https://www.youtube.com/watch?t=304s&v=LtlbB4-6k_U>" %}
Sean Allen / Swift - Class vs. Struct Explained
{% endembed %}

{% embed url="<https://www.youtube.com/watch?v=O0q06AEzgi0>" %}
Logan Koshenka / Swift Struct vs. Class Explained (iOS Interview Question)
{% endembed %}

### Articles / Documents

* [Hacking with Swift / 100 Days / Day-12 - How to copy classes](https://www.hackingwithswift.com/quick-start/beginners/how-to-copy-classes)
