inout Parameters क्या हैं
एक inout parameter एक function को बाहर से एक variable तक पहुंचने और असल में इसकी value बदलने देता है, सिर्फ इसे देखने की नहीं।
In this page:
Syntax
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
// 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)")
Login to try C/C++/Java/PHP code in the editor
Swapping Two Values
inout का एक classic उपयोग एक function है जो दो variables की values सीधे swap करता है, एक tuple return किए बिना।
Note:
Swift की standard library पहले से एक built-in
swap(_:_:) function प्रदान करती है जो बिल्कुल यही करता है।उदाहरण: Swapping Two Values
// 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)")
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. #}
आम गलतियां
- Call site पर एक
inoutparameter को एक variable pass करते समय&symbol भूल जाना -- mutation को explicit बनाने के लिए यह ज़रूरी है। - एक
letconstant या एक literal value को एकinoutargument के रूप में pass करने की कोशिश करना; सिर्फ एक mutable variable pass किया जा सकता है। - यह मान लेना कि
inoutdefault रूप से कुछ दूसरी languages की तरह एक reference pass करता है; Swift में इसे parameter list मेंinoutसे explicitly declare किया जाना चाहिए।
चैप्टर सारांश
- किसी parameter के type से पहले
inoutfunction को caller की original variable modify करने देता है। - Callers को यह acknowledge करने के लिए argument से पहले
&prefix करना चाहिए कि यह mutate हो सकता है। - सिर्फ variables (
var), constants या literals नहीं,inoutarguments के रूप में pass किए जा सकते हैं। inoutswap जैसे functions के लिए उपयोगी है जिन्हें अपने inputs सीधे modify करने चाहिए।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: