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

Type Inference क्या है

Type inference का मतलब है Swift सिर्फ इसे देखकर यह पता लगाने के लिए काफी smart है कि आप किस तरह की value store कर रहे हैं, बिना आपके यह कहने की ज़रूरत के।
Syntax
swift
let name = value    // type inferred from the value
var name = value

// name = otherTypeValue   // error: type is fixed

How Inference Works

जब आप let age = 25 लिखते हैं, Swift literal 25 देखता है और अपने आप type Int infer करता है, बिना आपके कहीं Int लिखे।

उदाहरण: How Inference Works

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

Types Are Still Fixed

भले ही आपने type explicitly नहीं लिखा, Swift अब भी इसे सख्ती से enforce करता है -- एक Int के रूप में inferred variable बाद में कभी एक String नहीं रख सकता।

Note: इसके बाद count = "ten" try करें और compiler इसे reject करेगा -- यही inference plus strict typing एक साथ काम कर रहा है।

उदाहरण: Types Are Still Fixed

markup
// Declare a mutable variable `count`, initialized to `3`
var count = 3
count = 10
// Print "count is now \(count), still an Int" to the console
print("count is now \(count), still an Int")

Inference with Collections

Type inference arrays और dictionaries के साथ भी काम करता है: Swift collection का element type infer करने के लिए elements देखता है।

उदाहरण: Inference with Collections

markup
let scores = [90, 85, 78]
print("Inferred as [Int]: \(scores)")
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. यह मानना कि Swift untyped है क्योंकि आप हमेशा type नहीं लिखते; हर value के पीछे अब भी एक strict, fixed type है।
  2. एक inferred type की एक value assign करना और बाद में उसी variable को एक अलग type assign करने की कोशिश करना, जो compile होने में fail होता है।
  3. यह न समझना कि एक expression में एक Int literal को एक Double के साथ mix करना एक explicit conversion को मजबूर करता है, क्योंकि inference चुपचाप types widen नहीं करेगा।
चैप्टर सारांश
  • Swift किसी variable का type अपने आप इसकी initial value से infer करता है।
  • एक बार infer होने पर, type fixed है -- आप बाद में एक अलग type की value assign नहीं कर सकते।
  • Type inference boilerplate घटाता है जबकि Swift को पूरी तरह statically typed रखता है।
  • आप हमेशा एक incompatible type assign करने की कोशिश करके और compiler error देखकर inferred behavior जांच सकते हैं।
🔒

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.