Type Annotations क्या हैं
In this page:
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
// 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)")
Login to try C/C++/Java/PHP code in the editor
Declaring Without an Initial Value
जब किसी variable को तुरंत एक value नहीं दी जाती, एक type annotation ज़रूरी है ताकि Swift जाने कि assign होने पर किस type की उम्मीद करनी है।
उदाहरण: Declaring Without an Initial Value
var total: Int
total = 100
// Print "Total is \(total)" to the console
print("Total is \(total)")
Login to try C/C++/Java/PHP code in the editor
Forcing a Different Type Than Inference Would Choose
कभी-कभी आप एक Double चाहते हैं भले ही एक whole number literal normally Int infer होता; एक explicit annotation यह choice आपके लिए करता है।
let wholeNumber = 5 Int के रूप में infer होता, Double नहीं।उदाहरण: Forcing a Different Type Than Inference Would Choose
let wholeNumber: Double = 5
print("Forced to Double: \(wholeNumber)")
Login to try C/C++/Java/PHP code in the editor
- आदतन हर single variable में एक type annotation जोड़ना, भले ही inference इसे पहले से obvious बना दे और annotation कोई clarity न जोड़े।
- Annotation लिखना लेकिन एक incompatible type की value supply करना, जैसे
let age: Int = "25"। - 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 जैसे
DoubleinferredIntके बजाय मजबूर करने के लिए। :के बाद का type बिल्कुल assigned value से match (या convertible) होना चाहिए।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: