← Back to Swift Course | Chapter 8: Structs & Classes | Lesson 1 of 9

Structs के Basics

एक struct आपका अपना custom kind of value बनाने के लिए एक blueprint है, related data के पीस को एक नाम के तहत एक साथ bundle करते हुए।
Syntax
swift
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

markup
// 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))")

Structs Are Value Types

जब एक struct instance एक नए variable को assign किया जाता है या किसी function में pass किया जाता है, इसका data copy हो जाता है, इसलिए copy में changes original को प्रभावित नहीं करते।

उदाहरण: Structs Are Value Types

markup
// 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)")
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. यह भूल जाना कि struct की stored properties को initializer खत्म होने से पहले सभी को values (या defaults) दी जानी चाहिए।
  2. एक let struct instance की property modify करने की कोशिश करना; let से declared होने पर पूरा instance immutable है।
  3. यह मान लेना कि structs shared references वाली classes की तरह behave करते हैं; structs value types हैं और assignment पर copy होते हैं।
चैप्टर सारांश
  • एक struct related properties और methods को एक single custom type में bundle करता है।
  • अगर आप अपना खुद का नहीं लिखते तो Structs को एक automatic memberwise initializer मिलता है।
  • Structs value types हैं: एक को एक नए variable को assign करना इसका data copy करता है।
  • एक let struct instance इसके सभी properties सहित पूरी तरह immutable है।
🔒

Chapter Quiz — Complete all 9 topics to unlock

0/9 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.