← Back to Swift Course | Chapter 5: Optionals | Lesson 6 of 8

Nil Coalescing Operator क्या है

Nil coalescing operator (??) कहता है "इस value का उपयोग करो, लेकिन अगर यह गायब है, तो इसके बजाय इस अन्य backup value का उपयोग करो।"
Syntax
swift
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

markup
// 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)")

Nil Coalescing with Chained Fallbacks

?? को chain किया जा सकता है ताकि अगर पहला optional nil हो, दूसरा try किया जाए, वगैरह, एक final guaranteed default तक।

उदाहरण: Nil Coalescing with Chained Fallbacks

markup
// 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)")
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. सिर्फ एक fallback default देने के लिए एक if-else block उपयोग करना जब ?? वही logic एक line में express कर देता।
  2. यह भूल जाना कि ?? का right-hand side optional के wrapped type से match करना चाहिए (या उस type का एक और optional)।
  3. यह मान लेते हुए कि operator precedence किसी expression के बाकी हिस्से के साथ left-to-right से अलग काम करता है गलत तरीके से ?? chain करना -- parentheses complex expressions को clarify करने में मदद करते हैं।
चैप्टर सारांश
  • a ?? b a तक 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:

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.