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

guard let Unwrapping क्या है

guard let जांचता है कि एक value मौजूद है, और अगर नहीं है, function बिना इसके continue करने की कोशिश करने के बजाय तुरंत निकल जाता है।
Syntax
swift
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

markup
// 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)

Chaining Multiple guard let Unwraps

कई optionals एक single guard let में unwrap किए जा सकते हैं, सभी commas से अलग, किसी function के top पर validation logic compact रखते हुए।

उदाहरण: Chaining Multiple guard let Unwraps

markup
// 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)
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. यह भूल जाना कि guard let की else branch को current scope exit करना चाहिए, बिल्कुल एक plain guard की तरह।
  2. guard let उपयोग करना किसी value के लिए जो सिर्फ एक छोटे block के अंदर संक्षिप्त रूप से चाहिए, जहां if let scope को tighter रखता।
  3. 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 let if let से ज़्यादा पसंद किया जाता है।
🔒

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.