Last active
October 5, 2020 16:48
-
-
Save andymuncey/f6fe94a3f952f3d0db40f118a6bbcc1f to your computer and use it in GitHub Desktop.
Demonstrates pass by reference vs pass by value difference with Swift struct and class
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
//change this to a struct and verify the change in behaviour | |
class Number : CustomStringConvertible { | |
var number: Int | |
init(_ num: Int) { | |
number = num | |
} | |
public var description : String { | |
return "\(number)" | |
} | |
//used to get description of type | |
var type : String { | |
return String(describing: Mirror(reflecting: self).displayStyle!) | |
} | |
} | |
var intA = Number(2) | |
var intB = intA //passing value by reference(class) or value(struct) | |
intA.number = 7 //reassign value of intA (intB will only be reassigned if passed by reference) | |
print("Working with \(intA.type)") | |
print("intA value: \(intA)") | |
print("intB value: \(intB)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment