nil Value की जानकारी
nil Swift का यह कहने का तरीका है कि "यहां बिल्कुल कुछ नहीं है," एक खाली gift box जैसा।
In this page:
Syntax
var name: Type? = value
name = nil
if name == nil {
// no value
}
Assigning nil
सिर्फ एक optional type से declared variable को nil सेट किया जा सकता है, यह represent करते हुए कि यह अभी कोई value नहीं रखता।
उदाहरण: Assigning nil
// 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)
Login to try C/C++/Java/PHP code in the editor
Checking for nil
किसी optional की तुलना == या != से nil के साथ करना यह जांचने का एक सीधा तरीका है कि यह अभी एक value रखता है या नहीं।
उदाहरण: Checking for nil
// 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!)")
}
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. #}
आम गलतियां
- एक non-optional variable को
nilassign करने की कोशिश करना; सिर्फ optional types कभीnilरख सकते हैं। - यह मान लेना कि Swift में
nil0या एक empty string की तरह behave करता है; यह specifically value की पूरी absence represent करता है। - यह भूल जाना कि बिना 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: