guard Statement की जानकारी
guard दरवाज़े पर एक bouncer जैसा है: अगर एक condition पूरी नहीं होती, code तुरंत आगे continue करने के बजाय निकल जाता है।
In this page:
Syntax
func name(param: Type) {
guard condition else {
// must exit: return, break, continue or throw
return
}
// continue when condition is true
}
Basic guard Syntax
एक guard statement एक condition जांचता है और, अगर यह false है, else block चलाता है -- जिसे current scope से exit होना चाहिए, आमतौर पर return से।
उदाहरण: Basic guard Syntax
// Define the function `describe` taking `age`
func describe(age: Int) {
guard age >= 0 else {
// Print "Invalid age" to the console
print("Invalid age")
return
}
// Print "Age is \(age)" to the console
print("Age is \(age)")
}
describe(age: 25)
describe(age: -5)
Login to try C/C++/Java/PHP code in the editor
guard for Early Exit Validation
guard किसी function में जल्दी कई conditions validate करने के लिए idiomatic है, main logic को unindented और follow करने में आसान रखते हुए।
Note:
एक
guard में कई conditions comma-separated हो सकते हैं, सभी pass होने के लिए true होने चाहिए।उदाहरण: guard for Early Exit Validation
// Define the function `processScore` taking `score`
func processScore(_ score: Int) {
guard score >= 0, score <= 100 else {
// Print "Score out of range" to the console
print("Score out of range")
return
}
// Print "Valid score: \(score)" to the console
print("Valid score: \(score)")
}
processScore(150)
processScore(85)
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. #}
आम गलतियां
- यह भूल जाना कि एक
guardblock केelseclause को current scope exit करना MUST है (return,break,continue, याthrowसे) -- Swift इसे compile time पर enforce करता है। guardउपयोग करना main happy-path logic के लिए बजाय validating और जल्दी exit करने के;guardearly exits के लिए है,ifbranching के लिए।- यह न समझना कि
guard letमें bound variables enclosing scope के बाकी हिस्से के लिए available रहते हैं, एकif letbinding के विपरीत जो अपने block तक scoped है।
चैप्टर सारांश
guardएक condition जांचता है और एकelseblock चाहता है जो condition fail होने पर scope से बाहर निकले।- यह आमतौर पर किसी function के top पर early-exit validation के लिए उपयोग होता है।
guard letसे unwrapped values function के बाकी हिस्से के लिए usable रहती हैं, nestedif letकी तुलना में readability बेहतर करते हुए।- Swift compiler enforce करता है कि एक
guardकीelsebranch को current scope छोड़ना चाहिए।
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: