skip to content

Collections and Core Protocols

The standard library's arrays, sets and dictionaries, the Sequence family, and the protocols that make types comparable, hashable and codable. Asked in every coding round.

on this pageshow

explore

questions

24

In Swift, how do you choose between Array, Set and Dictionary, and what does a membership or key lookup cost in each?

level: juniorimportance: must knowfreq 80%

answer

  1. order, uniqueness, lookup by key
  2. linear scan versus hash lookup
  3. Hashable elements and keys
  4. key subscript gives back an optional

basics

~20 s

Use Array for ordered values that may repeat, Set for unique values you test for membership, and Dictionary to find a value by key. Array.contains(:) is a linear scan; Set.contains(:) is O(1); a Dictionary key lookup returns an optional.

solid answer

~40 s

I pick by the question the code asks most often. If order matters or duplicates are allowed, it is an `Array`: reading by integer position is O(1), but `contains(_:)` walks every element, O(n). If I mostly ask "is this in there?" and duplicates make no sense, it is a `Set`: its `contains(_:)` is documented as O(1) and `insert(_:)` ignores a member that is already present. If I look things up by an identifier, it is a `Dictionary`: `dict[key]` returns `Value?` because the key may be missing. `Set` elements and `Dictionary` keys must be `Hashable`, and neither type keeps a stable insertion order, so anything displayed in order still needs an array.

code

swift · 28 lines
swift
struct Thumbnail {
    let id: Int
    let title: String
}

var thumbnails: [Thumbnail] = [
    Thumbnail(id: 7, title: "Beach"),
    Thumbnail(id: 3, title: "Harbour"),
    Thumbnail(id: 9, title: "Dunes"),
]
var selectedIDs: Set<Int> = []
var titleCache: [Int: String] = [:]

thumbnails.append(Thumbnail(id: 4, title: "Pier"))   // keeps display order
print(thumbnails[0].title)                            // "Beach": O(1) by position

selectedIDs.insert(9)
selectedIDs.insert(9)                                 // ignored: already a member
print(selectedIDs.count)                              // 1
print(selectedIDs.contains(9))                        // hash lookup, O(1)
print(thumbnails.contains { $0.id == 9 })             // linear scan, O(n)

titleCache[9] = "Dunes"
if let title = titleCache[3] {                        // String?, nil when missing
    print(title)
} else {
    print("cache miss for 3")
}

go deeper

for a junior

Recall which container answers which question: order, membership or lookup by key. Know that array contains is linear and set contains is constant time.

for a middle

Explain why hashing makes set and dictionary lookups constant time on average, what Hashable is needed for, and why iteration order of hashed collections is unpredictable.

for a senior

Spot a linear contains call inside a loop in a pull request and replace it with a one-time Set conversion, and justify the extra memory against the data sizes involved.

for a principal

Frame the choice as an access-pattern decision for shared model code: which lookups dominate, whether order is part of the contract, and what keeping two structures in sync costs.

## Three containers, three questions Swift's standard library ships three general-purpose collections, and all three are **value types** declared as structs: `Array<Element>`, `Set<Element>` and `Dictionary<Key, Value>`. Choosing between them is mostly a matter of which question your code asks most often. - **`Array`** keeps elements in the order you put them in and allows duplicates. Positions are integers from `0` up to, but not including, `count`. - **`Set`** keeps each value at most once and has no defined order. It exists to answer "is this value a member?" quickly. - **`Dictionary`** maps each unique key to one value, also with no defined order. It exists to answer "what is stored for this key?" The Swift book's chapter on collection types puts it in one line each: arrays are ordered collections of values, sets are unordered collections of unique values, and dictionaries are unordered collections of key-value associations. ## What each lookup costs The standard library documents complexity in a `Complexity:` line above each member, and those lines are what an interviewer expects you to know. | Operation | Cost or result | Why | |---|---|---| | `array[i]` (read) | O(1) | elements sit in one buffer, so the address is computed | | `array.contains(x)` | O(n) | `Sequence.contains(_:)` compares element by element | | `set.contains(x)` | O(1) | the element's hash picks the bucket | | `set.insert(x)` | returns `(inserted:memberAfterInsert:)` | a duplicate is not stored twice | | `dict[key]` | hash lookup, returns `Value?` | `nil` means the key is absent | The practical consequence: a loop that calls `array.contains(_:)` for each of *m* candidates against *n* elements does O(n * m) comparisons, while the same loop against a `Set` does about *m* hash lookups. Converting once, `Set(array)`, and then querying the set is the standard fix when membership checks dominate. ## A worked scenario: a photo gallery Imagine a gallery screen that shows thumbnails, lets the user select several, and caches titles fetched from disk. 1. The thumbnails are shown in a fixed order and the same photo may legitimately appear twice in different albums, so they live in an **array**. 2. The selected photo IDs have no order and a photo is either selected or not, so they live in a **set**. Tapping a thumbnail asks `selectedIDs.contains(id)` once per cell, which stays cheap however many photos are selected. 3. The title cache answers "what do I already know about photo 42?", so it is a **dictionary** keyed by ID. `titleCache[42]` returns `String?`; a `nil` is a cache miss, not a crash. The code example shows all three side by side. ## Requirements and trade-offs - **Hashable.** A `Set`'s elements and a `Dictionary`'s keys must conform to `Hashable`. Standard types such as `Int`, `String` and enums without associated values already do; how to write a correct conformance for your own type is covered in the lesson on equality and hashing. - **No order.** Iterating a set or a dictionary visits elements in an order the standard library calls stable between mutations but otherwise unpredictable. Never rely on it for display or for tests that compare printed output; sort first, or keep a separate array for order. - **Duplicates.** `Set.insert(_:)` returns a tuple whose `inserted` flag is `false` when the value was already present, so the set's count does not grow. - **Memory.** A hashed collection needs spare capacity to keep lookups fast, so for a handful of elements a plain array scan can be just as quick. Complexity matters as the data grows; for five items, pick what reads most clearly. - **Missing data.** An out-of-range array subscript traps at run time with `Index out of range`; a missing dictionary key just yields `nil`. That difference is why a dictionary is the natural shape for a cache. ## How to answer in an interview Name the question each container answers (order, membership, lookup by key), give the cost of `contains(_:)` on an array versus a set, mention that set elements and dictionary keys must be `Hashable`, and note that neither hashed collection preserves order. Then tie it to a concrete screen, like the gallery above, to show you choose by access pattern rather than by habit.

  • You need both fast membership checks and a stable display order. What do you keep?
    Keep both: an `Array` for the order and a `Set` (or a `Dictionary` keyed by ID) for the lookups, and update them together in one method so they cannot drift apart. The standard library has no ordered set type, so the pairing is the usual answer when you stay inside it.
  • Why does a set or dictionary print its contents in a different order than you inserted them?
    Both are hashed: the position of an element depends on its hash value, not on insertion time. The documentation calls the order stable between mutations but otherwise unpredictable, and hashing is seeded per process, so the order can differ between launches too. Sort before printing or comparing.

  • Calling contains(_:) on a large array inside a loop and calling it free
  • Expecting a Set or Dictionary to keep insertion order
  • Thinking a missing dictionary key traps like an out-of-range array index
  • Believing any type can be a Set element without Hashable
  • Choosing Dictionary with dummy values instead of a Set for membership
open as a page

In Swift, what does declaring Codable on a struct give you, and what must its stored properties satisfy to decode a flat JSON object?

level: juniorimportance: must knowfreq 80%

basics

~20 s

Codable (Encodable & Decodable) makes the compiler generate a CodingKeys enum, init(from:) and encode(to:) when every stored property's type conforms. Non-optional keys must be present; an Optional property decodes as nil when its key is missing or null.

open as a page

In Swift, when does the compiler synthesize Equatable and Hashable for your own type, and when must you write them yourself?

level: juniorimportance: must knowfreq 72%

basics

~20 s

Swift synthesizes == and hash(into:) when you declare Equatable or Hashable in the type's own file and every stored property (struct) or associated value (enum) conforms. Classes never get it; enums without payloads conform even undeclared.

open as a page

In Swift, what is the difference between map, compactMap and flatMap when you transform a sequence of values?

level: juniorimportance: must knowfreq 75%

basics

~10 s

Swift's map returns exactly one result per element; compactMap keeps only the non-nil results of a closure that returns an optional; flatMap concatenates the sequences its closure returns into one flat array.

open as a page

Swift's Array, Set and Dictionary are value types, so when does assigning or passing one actually copy its elements?

level: middleimportance: must knowfreq 72%

basics

~20 s

Assigning, passing or returning a standard collection copies only a reference to its shared storage. The elements are copied when a mutation hits storage that another copy still shares; a uniquely owned buffer is mutated in place.

open as a page

With Swift's JSONDecoder, how do CodingKeys and the .convertFromSnakeCase key strategy map snake_case keys, and why does combining them often throw keyNotFound?

level: middleimportance: must knowfreq 70%

basics

~20 s

CodingKeys raw values rename or skip properties; .convertFromSnakeCase rewrites each JSON key to camelCase before matching them. Combined, a raw value like "user_id" or a property named imageURL no longer matches the converted key, so decoding throws keyNotFound.

open as a page

In Swift, how do you sort contacts by last name and then first name, and what does each approach actually compare?

level: middleimportance: must knowfreq 58%

basics

~20 s

Compare tuples in a closure, sorted { ($0.lastName, $0.firstName) < ($1.lastName, $1.firstName) }, or make Contact Comparable with that < when the order is inherent. Foundation's KeyPathComparator sorts by key paths and compares Strings localized.

open as a page

After a server release, a Swift app's forecast list decode throws DecodingError.dataCorrupted at path [3].condition; what happened, and how do you make the decode tolerant?

level: seniorimportance: must knowfreq 60%

basics

~20 s

The fourth element's condition held a string no case of the String raw-value enum accepts, so synthesized decoding threw dataCorrupted and failed the whole array. A custom init(from:) mapping unknown strings to a case like unrecognized(String) makes it tolerant.

open as a page

In Swift, what does Array.append cost, when does reserveCapacity(_:) help, and why is removing from the front slow?

level: middleimportance: should knowfreq 50%

basics

~10 s

Array.append(:) is O(1) on average because storage grows geometrically. reserveCapacity(:) avoids repeated reallocations when the final size is known. insert(_:at: 0) and removeFirst() are O(n) because every later element shifts.

open as a page

With Swift's Dictionary, why does dict[key] return an optional, and when do you use the default subscript, grouping or uniquing initializers?

level: middleimportance: should knowfreq 60%

basics

~10 s

dict[key] returns Value? because the key may be absent, and assigning nil removes it. dict[key, default: v] supplies a fallback for counting; Dictionary(grouping:by:) buckets values; init(uniqueKeysWithValues:) traps on duplicate keys, while init(_:uniquingKeysWith:) merges them.

open as a page

Why does Swift's JSONDecoder at default settings throw typeMismatch on an ISO 8601 date string, and which dateDecodingStrategy fixes it?

level: middleimportance: should knowfreq 55%

basics

~20 s

The default .deferredToDate lets Date decode itself, which expects a number of seconds since 1 January 2001, so a string throws typeMismatch. Set dateDecodingStrategy to .iso8601, or to .custom when one payload mixes date formats.

open as a page

In Swift, how should you implement hash(into:) with Hasher, and why must a hashValue never be persisted across launches?

level: middleimportance: should knowfreq 50%

basics

~10 s

Implement hash(into:) by calling hasher.combine(_:) on exactly the members == compares. Hasher is randomly seeded per execution, so hashValue changes between launches and must never be stored in files, databases or caches.

open as a page

In Swift, how do ==, ===, ObjectIdentifier and Identifiable's id differ when deciding whether two contacts are the same?

level: middleimportance: should knowfreq 55%

basics

~20 s

== asks whether two values are equal under Equatable; === asks whether two class references point to the same instance; ObjectIdentifier makes that instance identity Hashable; Identifiable's id names a stable entity that survives edits.

open as a page

In a Swift analytics pipeline, why is reduce(into:_:) preferred over reduce(_:_:) when counting a day's events into a Dictionary?

level: middleimportance: should knowfreq 50%

basics

~20 s

With reduce(::) the closure must return a new Dictionary, and mutating a copy of a buffer the standard library still holds copies it on every element; reduce(into:_:) passes the Dictionary inout and mutates it in place.

open as a page

In Swift, what does conforming to Collection promise beyond Sequence, and why must an endless ID generator stay a plain Sequence?

level: middleimportance: should knowfreq 45%

basics

~20 s

Swift's Sequence only promises an iterator whose next() returns elements until nil; Collection adds nondestructive multipass access through indices, startIndex and endIndex, and every collection is finite, so an endless generator can only be a Sequence.

open as a page

In Swift, is sorted(by:) a stable sort, and what must its areInIncreasingOrder closure guarantee for the result to be correct?

level: middleimportance: should knowfreq 40%

basics

~10 s

Yes: Swift documents sort() and sorted(by:) as stable, so elements the predicate does not order keep their original relative order. The predicate must be a strict weak ordering, so less-or-equal comparisons break the guarantee.

open as a page

In Swift, why does page[0] trap when page is an ArraySlice taken from the middle of an array, and what does keeping that slice cost?

level: seniorimportance: should knowfreq 42%

basics

~20 s

An ArraySlice keeps its parent array's indices, so a slice of positions 2..<5 starts at index 2 and index 0 is out of bounds. A slice also references the parent's whole buffer, so storing it long-term keeps every parent element alive.

open as a page

A Swift app's weather API wraps each forecast in a "data" envelope with snake_case fields; how do you decode it into a flat struct with a custom init(from:)?

level: seniorimportance: should knowfreq 50%

basics

~20 s

In init(from:), open the root container with a RootKeys enum, call nestedContainer(keyedBy:forKey: .data) with a second key enum, and decode each field there, using decodeIfPresent with ?? for optional fields. Write a matching encode(to:) or the encoder writes a flat object.

open as a page

A Swift contacts importer deduplicates with a Set, yet contacts that compare equal with == survive as duplicates: why, and how do you fix it?

level: seniorimportance: should knowfreq 48%

basics

~20 s

Set picks a slot from the hash before it calls ==, so equal contacts with different hashes usually never get compared. Typical cause: a hand-written == beside a synthesized hash(into:) that hashes every stored property. Hash exactly what == compares.

open as a page

In Swift, why does subscripting an ArraySlice with the counter from enumerated() pick the wrong element or trap, and what should you use instead?

level: seniorimportance: should knowfreq 35%

basics

~20 s

enumerated() yields an Int counter starting at 0, not an index; an ArraySlice keeps its parent array's indices, so the counter points at the wrong element or past the bounds. Pair real indices with zip(slice.indices, slice).

open as a page

In Swift, when does adding .lazy to a map or filter chain save work, and why can its closure run more than once per element?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Swift's .lazy saves work when you read only part of a pipeline or make a single pass, because no intermediate arrays are built; the lazy view stores the closure, not results, so every read of an element runs it again.

open as a page

Should a Swift app's domain models conform to Codable directly, or should separate transfer types decode the API and be mapped into them?

level: principalimportance: should knowfreq 40%

basics

~20 s

Codable on domain models is cheapest when the app owns a stable format. For third-party or changing APIs, Decodable transfer types that mirror the JSON, mapped into domain types, keep CodingKeys, envelopes and open enums out of the model.

open as a page

As the lead of a Swift contacts app, how would you define equality, hashing and identity for the Contact model across deduplication, caching and diffing?

level: principalimportance: should knowfreq 30%

basics

~20 s

Keep Contact's == as full value equality, synthesized, and express identity through Identifiable's stable id. Put fuzzy import rules in named keys, key caches by id rather than hashValue or ObjectIdentifier, and ban hand-written == without matching hash(into:).

open as a page

When would you use Swift's ContiguousArray or Swift 6.2's InlineArray instead of Array, and what does each give up?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

ContiguousArray always uses contiguous native storage and never bridges to NSArray, which can help when Element is a class. InlineArray (Swift 6.2) stores a fixed count of elements inline, with no heap buffer, but copies eagerly and is not a Collection.

open as a page