Created
January 3, 2021 19:38
-
-
Save petermolnar-dev/bf9358c7a94242c753bf1aba0e42d7ca to your computer and use it in GitHub Desktop.
Value and reference type in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
var str = "Hello, playground" | |
var a = 1 | |
var b = a | |
b = b + 1 | |
/// Value of `a` doesn't change when the value of `b` changed. This is the default behaviour of Value types | |
print(a) | |
print(b) | |
class Person { | |
var name: String | |
init(name: String) { | |
self.name = name | |
} | |
} | |
var p_a = Person(name: "Peter") | |
var p_b = p_a | |
p_b.name = "Amos" | |
/// Whoops. The name of `p_a` has been change as well, when changing the name of `p_b`. That's the side effect of using Reference types. With that Swift type the actual variable only holding the memory address (reference) to the object. | |
print(p_a.name) | |
print(p_b.name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment