Initializers क्या हैं
एक initializer वह special setup code है जो आपके एक नया instance बनाने पर चलता है, यह सुनिश्चित करते हुए कि सब कुछ proper values के साथ शुरू हो।
In this page:
Syntax
struct TypeName {
var property: Type
init(property: Type) {
self.property = property
}
init?(input: Type) { // failable: may return nil
guard condition else { return nil }
self.property = input
}
}
Custom Initializer
एक custom init आपको बिल्कुल control करने देता है कि किसी instance की stored properties कैसे सेट होती हैं, validation logic सहित।
उदाहरण: Custom Initializer
// Define a struct `Person`
struct Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = max(0, age)
}
}
// Declare a constant `person`, set to `Person(name: "Alex", age: -5)`
let person = Person(name: "Alex", age: -5)
// Print "\(person.name) is \(person.age) years old" to the console
print("\(person.name) is \(person.age) years old")
Login to try C/C++/Java/PHP code in the editor
Failable Initializers
एक init? initializer nil return कर सकता है जब दिया input valid न हो, जो data parse या validate करते समय आम है।
उदाहरण: Failable Initializers
// Define a struct `PositiveNumber`
struct PositiveNumber {
let value: Int
init?(value: Int) {
guard value > 0 else { return nil }
self.value = value
}
}
// Declare a constant `good`, set to `PositiveNumber(value: 5)`
let good = PositiveNumber(value: 5)
// Declare a constant `bad`, set to `PositiveNumber(value: -3)`
let bad = PositiveNumber(value: -3)
// Print `good?.value as Any` to the console
print(good?.value as Any)
// Print `bad?.value as Any` to the console
print(bad?.value as Any)
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- यह भूल जाना कि किसी class initializer को कोई method call करने या return होने से पहले हर non-optional stored property सेट करनी चाहिए।
- किसी struct पर एक custom initializer लिखना और यह देखकर आश्चर्यचकित होना कि automatic memberwise initializer अब और available नहीं जब तक एक extension में declared न हो।
- एक failable initializer (
init?) जोnilreturn कर सकता है, को एक regular initializer के साथ confuse करना जो हमेशा succeed करता है।
चैप्टर सारांश
initdefine करता है कि एक instance कैसे बनता है और इसकी stored properties कैसे setup होती हैं।- Structs अपना automatic memberwise initializer खो देते हैं एक बार आप struct body के अंदर सीधे एक custom
initलिखें। - एक failable initializer,
init?लिखा गया, अगर setup fail हो तोnilreturn कर सकता है। - हर stored property को initialization के आखिर तक एक value होनी चाहिए।
🔒
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: