guard let Unwrapping क्या है
guard let जांचता है कि एक value मौजूद है, और अगर नहीं है, function बिना इसके continue करने की कोशिश करने के बजाय तुरंत निकल जाता है।
In this page:
Syntax
func name(param: Type?) {
guard let unwrapped = param else {
return
}
// use unwrapped
}
Basic guard let
guard let एक optional unwrap करता है और, अगर यह fail हो, else block execute करता है जिसे current scope छोड़ना चाहिए, आमतौर पर return के ज़रिए।
उदाहरण: Basic guard let
// Define the function `printUppercased` taking `text`
func printUppercased(_ text: String?) {
// Unwrap `text` into `text`, or bail out via the else branch
guard let text = text else {
// Print "No text provided" to the console
print("No text provided")
return
}
// Print `text.uppercased()` to the console
print(text.uppercased())
}
printUppercased("hello")
printUppercased(nil)
Login to try C/C++/Java/PHP code in the editor
Chaining Multiple guard let Unwraps
कई optionals एक single guard let में unwrap किए जा सकते हैं, सभी commas से अलग, किसी function के top पर validation logic compact रखते हुए।
उदाहरण: Chaining Multiple guard let Unwraps
// Define the function `describe` taking `name`, `age`
func describe(name: String?, age: Int?) {
// Unwrap `name, let age = age` into `name`, or bail out via the else branch
guard let name = name, let age = age else {
// Print "Missing information" to the console
print("Missing information")
return
}
// Print "\(name) is \(age) years old" to the console
print("\(name) is \(age) years old")
}
describe(name: "Kim", age: 28)
describe(name: nil, age: 28)
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. #}
आम गलतियां
- यह भूल जाना कि
guard letकीelsebranch को current scope exit करना चाहिए, बिल्कुल एक plainguardकी तरह। guard letउपयोग करना किसी value के लिए जो सिर्फ एक छोटे block के अंदर संक्षिप्त रूप से चाहिए, जहांif letscope को tighter रखता।guard letके सबसे बड़े फायदे का लाभ न उठाना -- unwrapped constant function के बाकी हिस्से के लिए available रहता है, nested indentation से बचते हुए।
चैप्टर सारांश
guard let value = optional else { return }unwrap करता है या current scope exit करता है।- यह "happy path" code को unindented और पढ़ने में आसान रखता है।
- Unwrapped constant enclosing function के बाकी हिस्से के लिए usable रहता है।
- जब एक missing value को execution जल्दी रोकना चाहिए तो
guard letif letसे ज़्यादा पसंद किया जाता है।
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: