← Back to Swift Course | Chapter 4: Functions | Lesson 1 of 7

Function के Basics

एक function steps की एक named recipe है जिसे आप जब चाहें चला सकते हैं, बस इसका नाम call करके।
Syntax
swift
func functionName(paramName: Type) -> ReturnType {
    return value
}

func functionName() {   // no return value
}

functionName(paramName: value)

Declaring and Calling a Function

एक function func, एक नाम, parentheses में parameters, और -> के बाद एक optional return type से define होता है।

उदाहरण: Declaring and Calling a Function

markup
// Define the function `greet` taking `name` and returning a String
func greet(name: String) -> String {
    // Return `"Hello, \(name)!"` from this function
    return "Hello, \(name)!"
}
// Print `greet(name: "Swift")` to the console
print(greet(name: "Swift"))

Functions Without a Return Value

एक function जो सिर्फ एक action perform करता है, बिना एक value produce किए, बस -> return type पूरी तरह omit कर देता है।

उदाहरण: Functions Without a Return Value

markup
// Define the function `printBanner` taking `title`
func printBanner(title: String) {
    // Print "=== \(title) ===" to the console
    print("=== \(title) ===")
}
printBanner(title: "Welcome")

Multiple Parameters

एक function कई parameters ले सकता है, हर एक अपने नाम और type के साथ, commas से अलग।

उदाहरण: Multiple Parameters

markup
// Define the function `add` taking `a`, `b` and returning an Int
func add(a: Int, b: Int) -> Int {
    // Return `a + b` from this function
    return a + b
}
// Print `add(a: 3, b: 4)` to the console
print(add(a: 3, b: 4))
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. Return type से पहले -> arrow भूल जाना, func add(a: Int, b: Int) -> Int के बजाय func add(a: Int, b: Int) Int लिखना।
  2. एक multi-statement function body के अंदर return छोड़ना; सिर्फ single-expression bodies इसे implicitly skip कर सकती हैं।
  3. एक function को उसके argument labels के बिना call करना जब वे ज़रूरी हों, जैसे add(a: a, b: b) के बजाय add(a, b) call करना।
चैप्टर सारांश
  • Functions func name(parameters) -> ReturnType { } से declare होते हैं।
  • Parameters और उनके types parentheses में list होते हैं, commas से अलग।
  • कोई meaningful return value न वाला function -> ReturnType हिस्सा छोड़ देता है (implicitly Void return करते हुए)।
  • किसी function को call करना इसके नाम के बाद parentheses में arguments उपयोग करता है, default रूप से labels उपयोग करते हुए।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.