Forced Unwrapping क्या है
Forced unwrapping अपने bare hands से optional box को फाड़ना जैसा है, यह मानते हुए कि आप 100% sure हैं कि अंदर कुछ है -- अगर आप गलत हैं, program crash हो जाता है।
Syntax
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
// 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)")
Login to try C/C++/Java/PHP code in the editor
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
// 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")
}
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 को force-unwrap करना बिना यह निश्चित हुए कि यह एक value रखता है, असल मेंnilहोने पर एक runtime crash का कारण बनते हुए।- Force unwrapping को optional binding या nil-coalescing जैसे safer alternatives के बजाय एक default आदत के रूप में उपयोग करना।
- एक dictionary lookup या failable initializer के result को force-unwrap करना, दोनों आमतौर पर
nilreturn करते हैं।
चैप्टर सारांश
- किसी 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: