Function के Basics
एक function steps की एक named recipe है जिसे आप जब चाहें चला सकते हैं, बस इसका नाम call करके।
Syntax
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
// 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"))
Login to try C/C++/Java/PHP code in the editor
Functions Without a Return Value
एक function जो सिर्फ एक action perform करता है, बिना एक value produce किए, बस -> return type पूरी तरह omit कर देता है।
उदाहरण: Functions Without a Return Value
// Define the function `printBanner` taking `title`
func printBanner(title: String) {
// Print "=== \(title) ===" to the console
print("=== \(title) ===")
}
printBanner(title: "Welcome")
Login to try C/C++/Java/PHP code in the editor
Multiple Parameters
एक function कई parameters ले सकता है, हर एक अपने नाम और type के साथ, commas से अलग।
उदाहरण: Multiple Parameters
// 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))
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. #}
आम गलतियां
- Return type से पहले
->arrow भूल जाना,func add(a: Int, b: Int) -> Intके बजायfunc add(a: Int, b: Int) Intलिखना। - एक multi-statement function body के अंदर
returnछोड़ना; सिर्फ single-expression bodies इसे implicitly skip कर सकती हैं। - एक 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हिस्सा छोड़ देता है (implicitlyVoidreturn करते हुए)। - किसी function को call करना इसके नाम के बाद parentheses में arguments उपयोग करता है, default रूप से labels उपयोग करते हुए।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: