AnyCompiler

Generics

Box<T> ek generic struct hai — T ek placeholder hai jo jahan bhi Box use hota hai wahan real type se fill ho jaata hai. Box("hello") argument se automatically Box<String> infer kar leta hai, aur compiler har use par type safety check karta hai — Array<Element> aur Dictionary<Key, Value> bhi under the hood isi idea par bane hain.

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 uspar.

Practice exercise

Ek generic struct Box<T> define karo jisme private var contents: T, ek init(_:), aur ek method getValue() -> T ho. let box = Box("hello") banao aur box.getValue() print karo.