Type Inference क्या है
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
// 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)")
Login to try C/C++/Java/PHP code in the editor
Types Are Still Fixed
भले ही आपने type explicitly नहीं लिखा, Swift अब भी इसे सख्ती से enforce करता है -- एक Int के रूप में inferred variable बाद में कभी एक String नहीं रख सकता।
count = "ten" try करें और compiler इसे reject करेगा -- यही inference plus strict typing एक साथ काम कर रहा है।उदाहरण: Types Are Still Fixed
// 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")
Login to try C/C++/Java/PHP code in the editor
Inference with Collections
Type inference arrays और dictionaries के साथ भी काम करता है: Swift collection का element type infer करने के लिए elements देखता है।
उदाहरण: Inference with Collections
let scores = [90, 85, 78]
print("Inferred as [Int]: \(scores)")
Login to try C/C++/Java/PHP code in the editor
- यह मानना कि Swift untyped है क्योंकि आप हमेशा type नहीं लिखते; हर value के पीछे अब भी एक strict, fixed type है।
- एक inferred type की एक value assign करना और बाद में उसी variable को एक अलग type assign करने की कोशिश करना, जो compile होने में fail होता है।
- यह न समझना कि एक 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: