Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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