Created
January 28, 2017 13:25
-
-
Save lukagabric/a2f3f7e812dc4017d9ff2258d1a2d122 to your computer and use it in GitHub Desktop.
Difference in value and reference type property setters
This file contains hidden or 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
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