Nil Coalescing Operator क्या है
Nil coalescing operator (??) कहता है "इस value का उपयोग करो, लेकिन अगर यह गायब है, तो इसके बजाय इस अन्य backup value का उपयोग करो।"
In this page:
Syntax
let result = optionalValue ?? defaultValue
let result = first ?? second ?? defaultValue
Basic Nil Coalescing
?? operator अगर मौजूद हो तो optional की value return करता है, या अगर optional nil है तो एक default value, सब एक concise expression में।
उदाहरण: Basic Nil Coalescing
// Declare a constant `userInput` (a `String?`), set to `nil`
let userInput: String? = nil
// Declare a constant `displayName`, set to `userInput ?? "Guest"`
let displayName = userInput ?? "Guest"
// Print "Welcome, \(displayName)" to the console
print("Welcome, \(displayName)")
Login to try C/C++/Java/PHP code in the editor
Nil Coalescing with Chained Fallbacks
?? को chain किया जा सकता है ताकि अगर पहला optional nil हो, दूसरा try किया जाए, वगैरह, एक final guaranteed default तक।
उदाहरण: Nil Coalescing with Chained Fallbacks
// Declare a constant `primary` (a `String?`), set to `nil`
let primary: String? = nil
// Declare a constant `secondary` (a `String?`), set to `nil`
let secondary: String? = nil
// Declare a constant `fallback`, set to `"[email protected]"`
let fallback = "[email protected]"
// Declare a constant `email`, set to `primary ?? secondary ?? fallback`
let email = primary ?? secondary ?? fallback
// Print "Using email: \(email)" to the console
print("Using email: \(email)")
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. #}
आम गलतियां
- सिर्फ एक fallback default देने के लिए एक
if-elseblock उपयोग करना जब??वही logic एक line में express कर देता। - यह भूल जाना कि
??का right-hand side optional के wrapped type से match करना चाहिए (या उस type का एक और optional)। - यह मान लेते हुए कि operator precedence किसी expression के बाकी हिस्से के साथ left-to-right से अलग काम करता है गलत तरीके से
??chain करना -- parentheses complex expressions को clarify करने में मदद करते हैं।
चैप्टर सारांश
a ?? baतक evaluate होता है अगर यह non-nil हो, अन्यथाbतक।??optionals के लिए default values देने का एक clean, single-line तरीका प्रदान करता है।- दाईं ओर का fallback value optional की wrapped value के बराबर (non-optional) type का होना चाहिए।
??को chain किया जा सकता है:a ?? b ?? cहर एक को बारी-बारी try करता है।
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: