Optional के Basics
एक optional एक box है जिसके अंदर कुछ हो सकता है, या पूरी तरह खाली हो सकता है -- और Swift आपसे देखने से पहले जांचवाता है।
In this page:
Syntax
var name: Type? = value
var name: Type? = nil // no value
func functionName() -> Type? {
return value or nil
}
Declaring an Optional
किसी type के बाद एक ? जोड़ना इसे optional चिह्नित करता है, मतलब variable उस type की एक value या nil दोनों में से कोई एक रख सकता है।
उदाहरण: Declaring an Optional
// Declare a mutable variable `middleName` (a `String?`), initialized to `"Marie"`
var middleName: String? = "Marie"
// Declare a mutable variable `nickname` (a `String?`), initialized to `nil`
var nickname: String? = nil
// Print `middleName as Any` to the console
print(middleName as Any)
// Print `nickname as Any` to the console
print(nickname as Any)
Login to try C/C++/Java/PHP code in the editor
Why Optionals Exist
Optionals type system में एक missing value की possibility को explicit बनाते हैं, आपको अनपेक्षित रूप से runtime पर crash होने के बजाय जानबूझकर nil case handle करने पर मजबूर करते हुए।
उदाहरण: Why Optionals Exist
// Define the function `findAge` taking `name` and returning a `Int?`
func findAge(for name: String) -> Int? {
// Declare a constant `ages`, set to `["Alice": 30, "Bob": 25]`
let ages = ["Alice": 30, "Bob": 25]
// Return `ages[name]` from this function
return ages[name]
}
// Print `findAge(for: "Alice") as Any` to the console
print(findAge(for: "Alice") as Any)
// Print `findAge(for: "Charlie") as Any` to the console
print(findAge(for: "Charlie") as Any)
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. #}
आम गलतियां
- एक optional value को सीधे underlying value की तरह treat करना, जैसे पहले unwrap किए बिना एक
Int?को एकIntमें जोड़ने की कोशिश करना। - पहले सुरक्षित रूप से
nilजांचने के बजाय आदतन हर optional को force-unwrap करना। Int?(एक optional Int) कोInt(एक guaranteed Int) के साथ confuse करना; compiler के लिए ये अलग-अलग types हैं।
चैप्टर सारांश
- एक optional
Type?लिखा जाता है और या तो एक value याnilरख सकता है। - Optionals किसी value की absence represent करने का Swift का explicit तरीका हैं।
- आप किसी optional की value पहले इसे unwrap किए बिना सीधे उपयोग नहीं कर सकते।
- Optionals दूसरी languages में आम null-reference crashes की एक पूरी category रोकते हैं।
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: