0
0
Swiftprogramming~5 mins

Struct declaration syntax in Swift

Choose your learning style9 modes available
Introduction

A struct lets you group related data together in one place. It helps organize information clearly and simply.

When you want to represent a simple object like a point with x and y coordinates.
When you need to group related values like a person's name and age.
When you want to create a custom data type that holds multiple pieces of information.
When you want to pass data around your program in a neat package.
When you want to keep your code organized and easy to understand.
Syntax
Swift
struct StructName {
    var property1: Type
    var property2: Type
    // more properties or methods
}

struct is the keyword to start a struct declaration.

Properties inside the struct hold the data. You can also add functions (methods) inside.

Examples
This struct defines a point with two integer properties: x and y.
Swift
struct Point {
    var x: Int
    var y: Int
}
This struct holds a person's name and age.
Swift
struct Person {
    var name: String
    var age: Int
}
This struct has properties and a method to calculate the area.
Swift
struct Rectangle {
    var width: Double
    var height: Double

    func area() -> Double {
        return width * height
    }
}
Sample Program

This program creates a Car struct, makes an instance, and prints its details.

Swift
struct Car {
    var make: String
    var year: Int
}

let myCar = Car(make: "Toyota", year: 2020)
print("My car is a \(myCar.year) \(myCar.make)")
OutputSuccess
Important Notes

Structs are value types, so when you copy them, you get a new copy.

You can add functions inside structs to work with their data.

Use structs for simple data grouping; use classes when you need inheritance or reference behavior.

Summary

Structs group related data into one named type.

Use struct keyword followed by properties inside curly braces.

Structs can have properties and methods to organize data and behavior.