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

nil Value की जानकारी

nil Swift का यह कहने का तरीका है कि "यहां बिल्कुल कुछ नहीं है," एक खाली gift box जैसा।
Syntax
swift
var name: Type? = value
name = nil

if name == nil {
    // no value
}

Assigning nil

सिर्फ एक optional type से declared variable को nil सेट किया जा सकता है, यह represent करते हुए कि यह अभी कोई value नहीं रखता।

उदाहरण: Assigning nil

markup
// Declare a mutable variable `favoriteColor` (a `String?`), initialized to `"blue"`
var favoriteColor: String? = "blue"
favoriteColor = nil
// Print `favoriteColor as Any` to the console
print(favoriteColor as Any)

Checking for nil

किसी optional की तुलना == या != से nil के साथ करना यह जांचने का एक सीधा तरीका है कि यह अभी एक value रखता है या नहीं।

उदाहरण: Checking for nil

markup
// Declare a mutable variable `score` (a `Int?`), initialized to `nil`
var score: Int? = nil
// Check whether `score == nil`
if score == nil {
    // Print "No score recorded yet" to the console
    print("No score recorded yet")
// Otherwise, run this branch
} else {
    // Print "Score is \(score!)" to the console
    print("Score is \(score!)")
}
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. एक non-optional variable को nil assign करने की कोशिश करना; सिर्फ optional types कभी nil रख सकते हैं।
  2. यह मान लेना कि Swift में nil 0 या एक empty string की तरह behave करता है; यह specifically value की पूरी absence represent करता है।
  3. यह भूल जाना कि बिना initial value के ताज़ा declared एक optional implicitly nil से शुरू होता है।
चैप्टर सारांश
  • nil किसी value की absence represent करता है और इसे सिर्फ optional types को assign किया जा सकता है।
  • एक non-optional variable कभी nil नहीं हो सकता -- compiler इसे compile time पर enforce करता है।
  • बिना initial value के declared एक optional default रूप से nil होता है।
  • if value == nil (या != nil) जांचना absence test करने का एक सरल तरीका है।
🔒

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.