Object Oriented Programming

Class Declaration in Swift

Classes are a blueprint for creating individual objects that contain the general characteristics of a defined object type. A modifier may or may not be used to declare a class.


Syntax
modifier class myClass { //class header

//fields, constructor

//method declarations

};

Notes

A constructor may or may not be included with a class.

The class body contains constructors for initializing new objects, declarations for the fields that provide the state of the class and its objects, and methods to implement the behaviour of the class and its objects.

Classes are reference type, which means they are passed around in code by reference.


Example
class hockeyScore {
    //fields
    var homeScore: Int
    var awayScore: Int

    //constructor
    init(homeScore: Int, awayScore: Int) {
        self.homeScore = homeScore
        self.awayScore = awayScore
    }

    //methods
    func homeGoal() {
        homeScore = homeScore + 1
    }

    func awayGoal() {
        awayGoal = awayGoal + 1
    }

   func getScore() -> (homeGoals: Int, awayGoals: Int) {
       return (homeScore, awayScore)
}

< Structures   |   Access Modifiers >

© 2019 SyntaxDB. All Rights Reserved.