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

inout Parameters क्या हैं

एक inout parameter एक function को बाहर से एक variable तक पहुंचने और असल में इसकी value बदलने देता है, सिर्फ इसे देखने की नहीं।
Syntax
swift
func functionName(_ param: inout Type) {
    param = newValue    // changes the caller's variable
}

var variable = value
functionName(&variable)

Declaring an inout Parameter

किसी parameter को inout चिह्नित करना function को caller द्वारा पास की गई original variable modify करने देता है, एक copy पर काम करने के बजाय।

उदाहरण: Declaring an inout Parameter

markup
// Define the function `doubleInPlace` taking `number`
func doubleInPlace(_ number: inout Int) {
    number *= 2
}
// Declare a mutable variable `value`, initialized to `5`
var value = 5
doubleInPlace(&value)
// Print "Doubled value: \(value)" to the console
print("Doubled value: \(value)")

Swapping Two Values

inout का एक classic उपयोग एक function है जो दो variables की values सीधे swap करता है, एक tuple return किए बिना।

Note: Swift की standard library पहले से एक built-in swap(_:_:) function प्रदान करती है जो बिल्कुल यही करता है।

उदाहरण: Swapping Two Values

markup
// Define the function `swapValues` taking `a`, `b`
func swapValues(_ a: inout Int, _ b: inout Int) {
    // Declare a constant `temp`, set to `a`
    let temp = a
    a = b
    b = temp
}
// Declare a mutable variable `x`, initialized to `1`
var x = 1
// Declare a mutable variable `y`, initialized to `2`
var y = 2
swapValues(&x, &y)
// Print "x=\(x), y=\(y)" to the console
print("x=\(x), y=\(y)")
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. Call site पर एक inout parameter को एक variable pass करते समय & symbol भूल जाना -- mutation को explicit बनाने के लिए यह ज़रूरी है।
  2. एक let constant या एक literal value को एक inout argument के रूप में pass करने की कोशिश करना; सिर्फ एक mutable variable pass किया जा सकता है।
  3. यह मान लेना कि inout default रूप से कुछ दूसरी languages की तरह एक reference pass करता है; Swift में इसे parameter list में inout से explicitly declare किया जाना चाहिए।
चैप्टर सारांश
  • किसी parameter के type से पहले inout function को caller की original variable modify करने देता है।
  • Callers को यह acknowledge करने के लिए argument से पहले & prefix करना चाहिए कि यह mutate हो सकता है।
  • सिर्फ variables (var), constants या literals नहीं, inout arguments के रूप में pass किए जा सकते हैं।
  • inout swap जैसे functions के लिए उपयोगी है जिन्हें अपने inputs सीधे modify करने चाहिए।
🔒

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.