← Back to Swift Course | Chapter 8: Structs & Classes | Lesson 7 of 9

Methods क्या हैं

एक method बस एक function है जो किसी struct या class से belong करता है, उस type को इसके खुद के actions देते हुए जो यह perform कर सकती है।
Syntax
swift
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

markup
// 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())")

Static Methods

एक static method type खुद से belong करता है, किसी particular instance से नहीं, और सीधे type name पर call किया जाता है।

उदाहरण: Static Methods

markup
// 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))
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. #}
आम गलतियां
  1. यह भूल जाना कि एक struct का method जो किसी property को modify करता है उसे explicitly mutating चिह्नित किया जाना चाहिए; classes को इसकी कभी ज़रूरत नहीं क्योंकि उनके methods हमेशा properties modify कर सकते हैं।
  2. एक instance method को एक type-level (static) method की तरह call करना, या इसका उल्टा।
  3. self. overuse करना जब disambiguation के लिए ज़रूरी न हो; Swift अक्सर इसे context से infer करता है, हालांकि यह closures और कुछ initializers के अंदर ज़रूरी है।
चैप्टर सारांश
  • एक instance method एक struct या class के अंदर defined एक function है, एक instance पर call किया गया।
  • एक static method किसी 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.