Generics
Box<T> ek generic struct hai — T ek placeholder hai jo jahan bhi Box istemal hota hai wahan real type se fill ho jata hai. Box("hello") argument se khud ba khud Box<String> infer kar leta hai, aur compiler har istemal par type safety check karta hai — Array<Element> aur Dictionary<Key, Value> bhi under the hood isi idea par bane hain.
Main.swift
Khud try karo →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
Aage: error handling, aur ek closing look is course ne kya cover kiya us par.
Practice exercise
Ek generic struct Box<T> define karein jis mein private var contents: T, ek init(_:), aur ek method getValue() -> T ho. let box = Box("hello") banayein aur box.getValue() print karein.