Generics
Box<T> is a generic struct — T is a placeholder filled in with a real type wherever Box is used. Box("hello") infers Box<String> automatically from the argument, with the compiler checking type safety at every use — the same idea Array<Element> and Dictionary<Key, Value> are built on under the hood.
Main.swift
Try it yourself →struct Box<T> {
private var contents: T
init(_ contents: T) {
self.contents = contents
}
func getValue() -> T {
return contents
}
}
let box = Box("hello")
print(box.getValue())Output
hello
Next: error handling, and a closing look at what this course covered.
Practice exercise
Define a generic struct Box<T> with a private var contents: T, an init(_:), and a method getValue() -> T. Create let box = Box("hello") and print box.getValue().