0
0
Swiftprogramming~5 mins

Class declaration syntax in Swift

Choose your learning style9 modes available
Introduction

Classes help you create your own types to group data and actions together. They let you build objects that can hold information and do things.

When you want to model real-world things like a car or a person with properties and actions.
When you need to create multiple objects that share the same structure and behavior.
When you want to organize your code by grouping related data and functions.
When you want to use inheritance to create a new class based on an existing one.
When you want to keep your code clean and easy to understand by using objects.
Syntax
Swift
class ClassName {
    // properties and methods go here
}

Class names start with a capital letter by convention.

Use curly braces { } to group the class content.

Examples
This class Dog has a property name and a method bark() that prints a sound.
Swift
class Dog {
    var name: String
    func bark() {
        print("Woof!")
    }
}
This Car class has a default color and a method to simulate driving.
Swift
class Car {
    var color: String = "Red"
    func drive() {
        print("Driving the car")
    }
}
Sample Program

This program defines a Person class with a name property and a greeting method. It creates a Person object named Alice and calls the greeting.

Swift
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
    func greet() {
        print("Hello, my name is \(name)")
    }
}

let person = Person(name: "Alice")
person.greet()
OutputSuccess
Important Notes

Use init to create a special method that sets up your class when you make a new object.

Use self to refer to the current object inside the class.

Summary

Classes group data and actions into one object.

Use class ClassName { } to declare a class.

Initialize properties with init and add functions to define behavior.