Structs के Basics
एक struct आपका अपना custom kind of value बनाने के लिए एक blueprint है, related data के पीस को एक नाम के तहत एक साथ bundle करते हुए।
In this page:
Syntax
struct TypeName {
var property: Type
let constant: Type
}
var instance = TypeName(property: value, constant: value) // memberwise init
instance.property
Defining and Using a Struct
एक struct named properties के साथ एक नया type declare करता है, और Swift अपने आप एक memberwise initializer generate करता है जो सभी properties को arguments के रूप में लेता है।
उदाहरण: Defining and Using a Struct
// Define a struct `Point`
struct Point {
var x: Int
var y: Int
}
// Declare a constant `origin`, set to `Point(x: 0, y: 0)`
let origin = Point(x: 0, y: 0)
// Print "Point at (\(origin.x), \(origin.y))" to the console
print("Point at (\(origin.x), \(origin.y))")
Login to try C/C++/Java/PHP code in the editor
Structs Are Value Types
जब एक struct instance एक नए variable को assign किया जाता है या किसी function में pass किया जाता है, इसका data copy हो जाता है, इसलिए copy में changes original को प्रभावित नहीं करते।
उदाहरण: Structs Are Value Types
// Define a struct `Point`
struct Point {
var x: Int
var y: Int
}
// Declare a mutable variable `pointA`, initialized to `Point(x: 1, y: 1)`
var pointA = Point(x: 1, y: 1)
// Declare a mutable variable `pointB`, initialized to `pointA`
var pointB = pointA
pointB.x = 99
// Print "A: \(pointA.x), B: \(pointB.x)" to the console
print("A: \(pointA.x), B: \(pointB.x)")
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. #}
आम गलतियां
- यह भूल जाना कि struct की stored properties को initializer खत्म होने से पहले सभी को values (या defaults) दी जानी चाहिए।
- एक
letstruct instance की property modify करने की कोशिश करना;letसे declared होने पर पूरा instance immutable है। - यह मान लेना कि structs shared references वाली classes की तरह behave करते हैं; structs value types हैं और assignment पर copy होते हैं।
चैप्टर सारांश
- एक
structrelated properties और methods को एक single custom type में bundle करता है। - अगर आप अपना खुद का नहीं लिखते तो Structs को एक automatic memberwise initializer मिलता है।
- Structs value types हैं: एक को एक नए variable को assign करना इसका data copy करता है।
- एक
letstruct instance इसके सभी properties सहित पूरी तरह immutable है।
🔒
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: