Mobile Development
Swift
Subjective
Oct 04, 2025
Explain the concept of copy-on-write in Swift collections.
Detailed Explanation
Copy-on-write (COW) is an optimization where Swift collections share memory until modification occurs.\n\n• **How It Works:**\n• Multiple variables share same memory\n• Copy only happens when one is modified\n• Reduces memory usage and improves performance\n• Automatic in Swift standard collections\n\n\nvar array1 = [1, 2, 3, 4, 5] // Original array\nvar array2 = array1 // Shares memory with array1\n\n// No copy yet - both point to same memory\nprint(array1) // [1, 2, 3, 4, 5]\nprint(array2) // [1, 2, 3, 4, 5]\n\n// Now copy happens\narray2.append(6) // Triggers copy\nprint(array1) // [1, 2, 3, 4, 5]\nprint(array2) // [1, 2, 3, 4, 5, 6]\n\n\n• **Benefits:**\n• Memory efficiency\n• Performance optimization\n• Transparent to developers\n• Maintains value semantics\n\n• **Custom Implementation:**\n\nstruct MyArray {\n var storage: ArrayStorage\n \n func append(_ element: T) {\n if !isKnownUniquelyReferenced(&storage) {\n storage = storage.copy()\n }\n storage.append(element)\n }\n}\n
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts