DevPrep

All topics › Programming basics

Prototype

Junior

Essence

A prototype is a ready-made sample object from which new objects are copied instead of being constructed from scratch. In languages with prototype-based inheritance (JavaScript) this is the core of the object model: an object points at its prototype and inherits its properties dynamically. Swift and Objective-C are class-based, so for an iOS developer "prototype" is first of all the Prototype pattern: cloning an object together with its state.

What it looks like in Swift

import Foundation

final class Document: NSCopying {
    var title: String
    var tags: [String]
    init(title: String, tags: [String]) { self.title = title; self.tags = tags }

    func copy(with zone: NSZone? = nil) -> Any {
        Document(title: title, tags: tags)    // we copy the fields ourselves
    }
}

let template = Document(title: "Report", tags: ["draft"])
let doc = template.copy() as! Document
doc.title = "Q3 report"
print(template.title)        // Report — the prototype is untouched

// For a struct the "prototype" is free: assignment already copies
struct Theme { var accent = "blue"; var font = "SF Pro" }
let base = Theme()
var dark = base
dark.accent = "purple"
print(base.accent, dark.accent)   // blue purple

Where it shows up on iOS

What the interviewer looks for

Can you tell prototype-based inheritance (JavaScript) apart from the Prototype pattern, and do you understand that in Swift only reference types need cloning, while for a struct it comes for free.

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