Skip to content

Instantly share code, notes, and snippets.

@petermolnar-dev
Created January 3, 2021 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petermolnar-dev/bf9358c7a94242c753bf1aba0e42d7ca to your computer and use it in GitHub Desktop.
Save petermolnar-dev/bf9358c7a94242c753bf1aba0e42d7ca to your computer and use it in GitHub Desktop.
Value and reference type in Swift
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