DevPrep

All topics › Object-oriented programming (OOP)

Collections and data structures in OOP

Junior

Essence

Collections are abstractions for storing groups of values: array, set, dictionary. In OOP languages such as Java they form a hierarchy of classes (the Collection Framework). Swift collections are built differently, and that difference is what the interviewer expects to hear.

Collections in Swift

var a = [1, 2, 3]
var b = a            // no copy yet: both share one buffer (copy-on-write)
b.append(4)          // the buffer is copied here, `a` is untouched
print(a, b)          // [1, 2, 3] [1, 2, 3, 4]

// Any type can join the collection family by adopting the protocols.
struct Countdown: Sequence, IteratorProtocol {
    var count: Int
    mutating func next() -> Int? {
        guard count > 0 else { return nil }
        defer { count -= 1 }
        return count
    }
}
print(Array(Countdown(count: 3)))                   // [3, 2, 1]
print(Countdown(count: 5).filter { $0.isMultiple(of: 2) }) // [4, 2]

Operation complexity

What the interviewer looks for

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store