Structs Aur Classes
Swift aapko custom type define karne ke do tareeke deta hai: struct aur class. Farq wohi value-versus-reference wala hai jo C# apne struct versus class se dikhata hai — lekin jahan C# struct ko occasional opt-in manta hai, Swift ki apni standard library types (String, Array, Dictionary, Int) sari structs hain, aur Swift ki apni style guides struct ko default choice recommend karti hain — class ka istemal sirf tab karein jab aapko khas taur par 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)1 100
modifyPoint(p1) sirf apni local copy ko touch karta hai — p1 khud kabhi change nahi hota, isi wajah se ye ab bhi 1 print karta hai. modifyBox(b1) iske bajaye wohi Box ka ek reference receive karta hai, isi liye baad mein change nazar aata hai: 100. Note karein ke Point ko explicit init ki zaroorat nahi thi — structs apni stored properties se free, khud ba khud initializer pate hain, jabke Box (ek class) ko hath se likha hua init chahiye tha.
Aage: mutating methods — struct ke apne methods default mein us ki properties kyun change nahi kar sakte, aur fix bhoolne se milne wala real compile error.
Practice exercise
Ek struct Point naam ka define karein jis mein var x: Int aur var y: Int ho. let p = Point(x: 3, y: 4) banayein aur p.x aur p.y istemal karke "3,4" print karein.