Methods क्या हैं
एक method बस एक function है जो किसी struct या class से belong करता है, उस type को इसके खुद के actions देते हुए जो यह perform कर सकती है।
In this page:
Syntax
struct TypeName {
func methodName(param: Type) -> ReturnType {
return value
}
static func typeMethod() { }
}
instance.methodName(param: value)
TypeName.typeMethod()
Defining an Instance Method
एक instance method किसी type के अंदर func से declare होता है, और dot syntax उपयोग करके उस type के एक specific instance पर call किया जाता है।
उदाहरण: Defining an Instance Method
// Define a struct `Circle`
struct Circle {
var radius: Double
// Define the function `area` with no parameters and returning a Double
func area() -> Double {
// Return `Double.pi * radius * radius` from this function
return Double.pi * radius * radius
}
}
// Declare a constant `circle`, set to `Circle(radius: 3)`
let circle = Circle(radius: 3)
// Print "Area: \(circle.area())" to the console
print("Area: \(circle.area())")
Login to try C/C++/Java/PHP code in the editor
Static Methods
एक static method type खुद से belong करता है, किसी particular instance से नहीं, और सीधे type name पर call किया जाता है।
उदाहरण: Static Methods
// Define a struct `MathHelper`
struct MathHelper {
static func square(_ n: Int) -> Int {
// Return `n * n` from this function
return n * n
}
}
// Print `MathHelper.square(6)` to the console
print(MathHelper.square(6))
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- यह भूल जाना कि एक struct का method जो किसी property को modify करता है उसे explicitly
mutatingचिह्नित किया जाना चाहिए; classes को इसकी कभी ज़रूरत नहीं क्योंकि उनके methods हमेशा properties modify कर सकते हैं। - एक instance method को एक type-level (static) method की तरह call करना, या इसका उल्टा।
self.overuse करना जब disambiguation के लिए ज़रूरी न हो; Swift अक्सर इसे context से infer करता है, हालांकि यह closures और कुछ initializers के अंदर ज़रूरी है।
चैप्टर सारांश
- एक instance method एक struct या class के अंदर defined एक function है, एक instance पर call किया गया।
- एक
staticmethod किसी single instance के बजाय type खुद से belong करता है। - Struct methods जो properties modify करते हैं उन्हें
mutatingचिह्नित किया जाना चाहिए। - Class methods हमेशा बिना किसी special keyword के properties modify कर सकते हैं।
🔒
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: