AnyCompiler

Structs Aur Classes

Swift aapko custom type define karne ke do tareeke deta hai: struct aur class. Farq wahi value-versus-reference wala hai jo C# apne struct versus class se dikhata hai — lekin jahan C# struct ko occasional opt-in maanta hai, Swift ki apni standard library types (String, Array, Dictionary, Int) saari structs hain, aur Swift ki apni style guides struct ko default choice recommend karti hain — class ka use sirf tab karein jab aapko specifically reference semantics ya inheritance chahiye.

struct Point {
    var x: Int
    var y: Int
}
class Box {
    var value: Int
    init(value: Int) {
        self.value = value
    }
}
func modifyPoint(_ p: Point) {
    var copy = p
    copy.x = 100
}
func modifyBox(_ b: Box) {
    b.value = 100
}
var p1 = Point(x: 1, y: 2)
modifyPoint(p1)
print(p1.x)

let b1 = Box(value: 1)
modifyBox(b1)
print(b1.value)
Output
1
100

modifyPoint(p1) sirf apni local copy ko touch karta hai — p1 khud kabhi change nahi hota, isliye ye abhi bhi 1 print karta hai. modifyBox(b1) iske bajaye same Box ka ek reference receive karta hai, isliye baad mein change visible hota hai: 100. Note karein ki Point ko explicit init ki zaroorat nahi thi — structs apni stored properties se free, automatic initializer paate hain, jabki Box (ek class) ko hand se likha hua init chahiye tha.

Aage: mutating methods — struct ke apne methods default mein uski properties kyun change nahi kar sakte, aur fix bhoolne se milne wala real compile error.

Practice exercise

Ek struct Point naam ka define karo jisme var x: Int aur var y: Int ho. let p = Point(x: 3, y: 4) banao aur p.x aur p.y use karke "3,4" print karo.