Last active
December 26, 2025 07:03
-
-
Save Roshankumar350/1b0111ae4978920fbfeefb7518d20fe5 to your computer and use it in GitHub Desktop.
Copy on write:
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
| class Person { | |
| var name: String | |
| init(name: String) { | |
| self.name = name | |
| } | |
| } | |
| let person1 = Person(name: "Mike") | |
| let person2 = person1 | |
| let address1 = Unmanaged.passUnretained(person1).toOpaque() | |
| let address2 = Unmanaged.passUnretained(person2).toOpaque() | |
| // Both are same | |
| print("Person1: \(address1)") | |
| print("Person2: \(address2)") | |
| struct Animal { | |
| var name: String | |
| } | |
| var animal1 = Animal(name: "Tiger") | |
| var animal2 = animal1 | |
| // Both are not same | |
| withUnsafeBytes(of: &animal1) { pointer in | |
| print("Animal1: \(pointer)") | |
| } | |
| withUnsafeBytes(of: &animal2) { pointer in | |
| print("Animal2: \(pointer)") | |
| } |
Author
Author
var array1 = Array(repeating: 1, count: 1000)
var array2 = array1 // This is a "Value Type" copy
print("--- Before Modification ---")
// Both will print same
array1.withUnsafeBufferPointer { pointer in
print("array1: \(pointer)")
}
array2.withUnsafeBufferPointer { pointer in
print("array2: \(pointer)")
}
// 2. Modify array2
print("\n--- After Modification ---")
array2.append(2)
// Both will print different
array1.withUnsafeBufferPointer { pointer in
print("array1: \(pointer)")
}
array2.withUnsafeBufferPointer { pointer in
print("array2: \(pointer)")
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
But, In value types like Arrays, Dictionaries, and Strings use a special trick. Even though they are structs, they don't actually copy their internal data until you try to modify one of them.
Before modification: Both structs point to the same internal "storage" on the heap.
After modification: The copy is physically made.