Protocols
Ek protocol methods ya properties ka ek set define karta hai jo ek type ko provide karna zaroori hota hai. Class inheritance ke unlike, jo sirf classes use kar sakti hain, structs aur classes dono ek protocol ko conform kar sakte hain — ye wahi hai jise Swift protocol-oriented programming kehta hai: jahan tak possible ho, deep class hierarchies ke bajaye lightweight protocol conformance ko favor karna.
protocol Shape {
func area() -> Double
}
struct Circle: Shape {
var radius: Double
func area() -> Double {
return Double.pi * radius * radius
}
}
struct Square: Shape {
var side: Double
func area() -> Double {
return side * side
}
}
let shapes: [Shape] = [Circle(radius: 2), Square(side: 3)]
for shape in shapes {
print(shape.area())
}12.566370614359172 9.0
Circle aur Square dono structs hain — value types, jinka koi shared base class bilkul nahi hai — lekin kyunki dono Shape ko conform karte hain, Shape ka ek array dono mein se koi bhi hold kar sakta hai, aur loop har ek ka apna area() implementation call karta hai.
Aage: enums — associated values wale enums, jo ek typical named-constant enum se genuinely zyada powerful hain.
Practice exercise
Ek protocol Named define karo jisme ek method getName() -> String ho. Ek struct Dog: Named define karo jisme var dogName: String ho aur ye protocol ko conform kare. Ek function greet(_ n: Named) likho jo "Hello, \(n.getName())" print kare, aur greet(Dog(dogName: "Rex")) call karo.