Generics
Generic Structs
A generic type stores the same shape of data for different value types.
Store a typed value
generic_structs.swift
Replay: real traced execution (multi-file project)
struct Box<Value> {
let value: Value
func label() -> String {
return "box=\(value)"
}
}
let storedValue = 10
let box = Box(value: storedValue)
let message = box.label()
print(message)
struct Box<Value> {
let value: Value
func label() -> String {
return "box=\(value)"
}
}
let storedValue = 4
let box = Box(value: storedValue)
let message = box.label()
print(message)
struct Box<Value> {
let value: Value
func label() -> String {
return "box=\(value)"
}
}
let storedValue = 22
let box = Box(value: storedValue)
let message = box.label()
print(message)
storedValue ← 10, box ← Box<Int>(value: 10)
9let storedValue→ 10 = 10 //@storedValue=4, 2210let box→ Box<Int>(value: 10) = Box(value: storedValue10)11let message = boxBox<Int>(value: 10).label()func label() -> String
4func label() -> String {5 return "box=\(value10)"6}message ← box=10
10let box = Box(value: storedValue)11let message→ box=10 = boxBox<Int>(value: 10).label()1213print(messagebox=10)outputbox=10
storedValue ← 4, box ← Box<Int>(value: 4)
9let storedValue→ 4 = 410let box→ Box<Int>(value: 4) = Box(value: storedValue4)11let message = boxBox<Int>(value: 4).label()func label() -> String
4func label() -> String {5 return "box=\(value4)"6}message ← box=4
10let box = Box(value: storedValue)11let message→ box=4 = boxBox<Int>(value: 4).label()1213print(messagebox=4)outputbox=4
storedValue ← 22, box ← Box<Int>(value: 22)
9let storedValue→ 22 = 2210let box→ Box<Int>(value: 22) = Box(value: storedValue22)11let message = boxBox<Int>(value: 22).label()func label() -> String
4func label() -> String {5 return "box=\(value22)"6}message ← box=22
10let box = Box(value: storedValue)11let message→ box=22 = boxBox<Int>(value: 22).label()1213print(messagebox=22)outputbox=22
generic type
The type argument is chosen when the generic type is used, so each instance keeps a concrete value type.