Last active
May 23, 2017 14:24
-
-
Save erenkabakci/a59821a6fd329f04cc972a66666f7667 to your computer and use it in GitHub Desktop.
Value vs Reference Type in Swift
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
//: Playground - noun: a place where people can play | |
// Value Type | |
struct StructA { | |
var field1: String = "Default Struct Value" | |
let field2: Int = 1 | |
} | |
let constantStruct = StructA() | |
var variableStruct = constantStruct | |
print(variableStruct.field1) // Same values with the constant value | |
variableStruct.field1 = "Changed mutable member of a mutable value type" // copy-on-write | |
print(constantStruct.field1) // Original value of the value type is not affected because of copy characteristic on value types | |
print(variableStruct.field1) | |
// Reference Type | |
class ClassA { | |
var field1: String = "Default Class Value" | |
} | |
let constantClass = ClassA() | |
var variableClass = constantClass | |
print(variableClass.field1) // Same values with the constant value | |
variableClass.field1 = "Changed mutable member of a mutable reference type" | |
print(constantClass.field1) // Original value of the constant type is also changed since they share the same references | |
print(variableClass.field1) | |
constantClass.field1 = "Assigned a new value to a mutable member of an `immutable` reference type" // Mutating members of an `immutable` reference type is still allowed eventhough they are defined as `let` | |
print(constantClass.field1) | |
print(variableClass.field1) // Value is updated for the reference as well. They always share same pointers. | |
/* Compile-time errors for assignments. Following assignments are not allowed. That is why using structs are safer than classes depending on the context. | |
It prevents side-effects and generates more compile time error for early recovery. | |
*/ | |
//constantStruct.field1 = "Cannot assign a value to a mutable member of a immutable value type" | |
//constantStruct.field2 = "Cannot assign a value to a immutable member of a immutable value type" | |
// | |
//constantClass = variableClass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment