← Back to Swift Course | Chapter 2: Variables & Types | Lesson 3 of 8

Type Annotations क्या हैं

एक type annotation तब है जब आप Swift को बिल्कुल बताते हैं कि एक variable किस तरह की value रखेगा, इसे guess करने देने के बजाय।
Syntax
swift
let name: Type = value
var name: Type            // no value yet
name = value

Basic Type Annotation Syntax

एक type annotation variable के नाम के बाद एक colon और type से follow होता है, inference पर भरोसा करने के बजाय intended type को explicit बनाते हुए।

उदाहरण: Basic Type Annotation Syntax

markup
// Declare a constant `age` (an Int), set to `25`
let age: Int = 25
// Declare a constant `price` (a Double), set to `9.99`
let price: Double = 9.99
// Declare a constant `name` (a String), set to `"Swift"`
let name: String = "Swift"
// Print "\(name) costs \(price), age category \(age)" to the console
print("\(name) costs \(price), age category \(age)")

Declaring Without an Initial Value

जब किसी variable को तुरंत एक value नहीं दी जाती, एक type annotation ज़रूरी है ताकि Swift जाने कि assign होने पर किस type की उम्मीद करनी है।

उदाहरण: Declaring Without an Initial Value

markup
var total: Int
total = 100
// Print "Total is \(total)" to the console
print("Total is \(total)")

Forcing a Different Type Than Inference Would Choose

कभी-कभी आप एक Double चाहते हैं भले ही एक whole number literal normally Int infer होता; एक explicit annotation यह choice आपके लिए करता है।

Note: Annotation के बिना, let wholeNumber = 5 Int के रूप में infer होता, Double नहीं।

उदाहरण: Forcing a Different Type Than Inference Would Choose

markup
let wholeNumber: Double = 5
print("Forced to Double: \(wholeNumber)")
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. आदतन हर single variable में एक type annotation जोड़ना, भले ही inference इसे पहले से obvious बना दे और annotation कोई clarity न जोड़े।
  2. Annotation लिखना लेकिन एक incompatible type की value supply करना, जैसे let age: Int = "25"।
  3. Colon syntax भूल जाना और let age: Int = 25 के बजाय let age Int = 25 लिखना।
चैप्टर सारांश
  • एक type annotation variable नाम के बाद : Type उपयोग करता है, जैसे let age: Int।
  • Annotations ज़रूरी होते हैं जब infer करने के लिए कोई initial value न हो।
  • Annotations clarity के लिए उपयोगी हैं, या एक specific type जैसे Double inferred Int के बजाय मजबूर करने के लिए।
  • : के बाद का type बिल्कुल assigned value से match (या convertible) होना चाहिए।
🔒

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.