Generics
Box<T> es un struct genérico — T es un marcador de posición que se rellena con un tipo real dondequiera que se use Box. Box("hello") infiere Box<String> automáticamente a partir del argumento, con el compilador verificando la seguridad de tipos en cada uso — la misma idea sobre la que se construyen internamente Array<Element> y Dictionary<Key, Value>.
Main.swift
Pruébalo tú mismo →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
A continuación: manejo de errores, y una mirada final a lo que cubrió este curso.
Practice exercise
Define un struct genérico Box<T> con una private var contents: T, un init(_:), y un método getValue() -> T. Crea let box = Box("hello") e imprime box.getValue().