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

Forced Unwrapping क्या है

Forced unwrapping अपने bare hands से optional box को फाड़ना जैसा है, यह मानते हुए कि आप 100% sure हैं कि अंदर कुछ है -- अगर आप गलत हैं, program crash हो जाता है।
Syntax
swift
let name: Type? = value
let unwrapped = name!    // crashes if name is nil

Force-Unwrapping a Known Value

जब आप निश्चित हों कि एक optional एक value रखता है, ! जोड़ना सीधे उस underlying value को निकालता है।

उदाहरण: Force-Unwrapping a Known Value

markup
// Declare a constant `possibleNumber` (a `Int?`), set to `42`
let possibleNumber: Int? = 42
// Declare a constant `number`, set to `possibleNumber!`
let number = possibleNumber!
// Print "Unwrapped number: \(number)" to the console
print("Unwrapped number: \(number)")

The Danger of Force-Unwrapping nil

असल में nil वाले एक optional को force-unwrap करना एक तुरंत runtime crash का कारण बनता है, इसलिए इसे उन cases के लिए reserved रखना चाहिए जहां value की guarantee हो।

Note: जब भी किसी value के मौजूद होने में कोई शक हो तो ! के बजाय if let या guard let पसंद करें।

उदाहरण: The Danger of Force-Unwrapping nil

markup
// Declare a constant `safeValue` (a `Int?`), set to `10`
let safeValue: Int? = 10
// Check whether `safeValue != nil`
if safeValue != nil {
    // Print "Safe to unwrap: \(safeValue!)" to the console
    print("Safe to unwrap: \(safeValue!)")
// Otherwise, run this branch
} else {
    // Print "Would have crashed if forced" to the console
    print("Would have crashed if forced")
}
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. ! से एक optional को force-unwrap करना बिना यह निश्चित हुए कि यह एक value रखता है, असल में nil होने पर एक runtime crash का कारण बनते हुए।
  2. Force unwrapping को optional binding या nil-coalescing जैसे safer alternatives के बजाय एक default आदत के रूप में उपयोग करना।
  3. एक dictionary lookup या failable initializer के result को force-unwrap करना, दोनों आमतौर पर nil return करते हैं।
चैप्टर सारांश
  • किसी optional value के बाद ! जोड़ना इसे force-unwrap करता है, underlying value निकालते हुए।
  • अगर optional force-unwrap करते समय nil है, program तुरंत crash हो जाता है।
  • Forced unwrapping सिर्फ तब उपयोग किया जाना चाहिए जब आप निश्चित हों कि value मौजूद है।
  • if let, guard let, और ?? जैसे safer alternatives आमतौर पर पसंद किए जाते हैं।
🔒

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.