Skip to content

Instantly share code, notes, and snippets.

@lukagabric
Created January 28, 2017 13:25
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 lukagabric/a2f3f7e812dc4017d9ff2258d1a2d122 to your computer and use it in GitHub Desktop.
Save lukagabric/a2f3f7e812dc4017d9ff2258d1a2d122 to your computer and use it in GitHub Desktop.
Difference in value and reference type property setters
public struct MyValueType {
public var name: String = "My name"
mutating func update(name newName: String) {
name = newName
}
}
public class MyReferenceType {
public var name: String = "My name"
public func update(name newName: String) {
name = newName
}
}
public class MyClass {
private var _myValueType = MyValueType()
public var myValueType: MyValueType {
get {
return _myValueType
}
set {
_myValueType = newValue
}
}
private var _myReferenceType = MyReferenceType()
public var myReferenceType: MyReferenceType {
get {
return _myReferenceType
}
set {
_myReferenceType = newValue
}
}
//Array is a value type so let's test the concept above
private var _names = [String]()
public var names: [String] {
get {
return _names
}
set {
_names = newValue
}
}
}
let myClass = MyClass()
myClass.myReferenceType = MyReferenceType()
myClass.myReferenceType.name = "some name"
myClass.myReferenceType.update(name: "some other name")
myClass.myValueType = MyValueType(name: "initial name")
myClass.myValueType.name = "some name"
myClass.myValueType.update(name: "some other name")
myClass.names = ["c", "b"]
myClass.names.append("a")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment