Prototype
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
NSCopying/copy()is Foundation's protocol for cloning class instances;NSString,NSArray,UIFontuse it. The@NSCopyingattribute on a property copies the assigned value automatically.- For value types the pattern is unnecessary: copying is built into the language semantics. That is one reason Swift models are usually structs.
- Deep vs shallow copy: by default
copy()does not clone nested class instances — you have to do that explicitly.
Where it shows up on iOS
- Settings templates, styles, request configurations (
URLRequestis a struct and copies itself). - Prototype cells in a storyboard — a sample cell the table creates instances from (in practice
dequeueReusableCellinstantiates them rather than copying).
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.