🍎 Swift & iOS Intermediate

What is memory management in Swift collections?

Why Interviewers Ask This

Mid-level Swift & iOS roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

Understanding memory management in Swift collections — especially copy-on-write (COW) — is important for performance. Value type collections (Array, Dictionary, Set): these are value types (structs) and use Copy-On-Write (COW). Assigning creates a logical copy, but actual memory copying happens only when one of the copies is mutated: var array1 = [1, 2, 3, 4, 5] var array2 = array1 // No copy yet -- both share same storage // Now mutate array2: array2.append(6) // NOW it copies -- array1 unaffected print(array1.count) // 5 print(array2.count) // 6. Performance implications: // Efficient: var result = someArray // No copy -- COW result.append(item) // Copy happens here only if shared // Avoid: var copy = originalArray // Shared for i in 0..<copy.count { copy[i] *= 2 // May copy multiple times if shared! } // Better: var copy = originalArray copy.withUnsafeMutableBufferPointer { buffer in for i in buffer.indices { buffer[i] *= 2 } }. Reference type elements in value type collections: var array1 = [NSMutableString("hello")] var array2 = array1 // Copy of the array (new array storage) array2[0].append(" world") // Mutates the SAME NSMutableString! print(array1[0]) // "hello world" -- affected because element is reference type. The array is copied but elements (reference types) are not. Lazy collections: let lazyMapped = (1...1000000).lazy.map { $0 * 2 } // No memory allocated until iterated. Use lazy for large collections to avoid creating intermediate arrays.

Pro Tip

This topic has Swift & iOS-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.