Skip to main content
Swift - iOS

Classes, Objects, Initializers, Enumeration & Inheritance.

By January 31, 2018December 26th, 2019No Comments

This post contains certain important aspects like basics of creating classes and objects and other relevant material.

Create a class

// Created a class and set its properties.

class Car {

var color : "Black"
var seats : 5

}

Enumeration : Basically creating a new data type.

// creating an enum

enum CarType {
case Sedan
case Coupe
case Hatchback
}


// Further can be used in class - example 

class Car {
        
    var color = "Black"
    var numberOfSeats : Int = 5
    
    // Using the data type created using enum
    
    var typeOfCar : CarType = .Coupe
}

Designated initializers

class Car {
    
    var color = "Black"
    var numberOfSeats : Int = 5
   

    var typeOfCar : CarType = .Coupe
    
    // Creating an initialiser which is designated(compulsory)
    
    init(customerChosenColor : String) {
        color = customerChosenColor
    }
}

Convenience initializers

class Car {
    
    var color = "Black"
    var numberOfSeats : Int = 5
   
    var typeOfCar : CarType = .Coupe

    
    init(customerChosenColor : String) {
        color = customerChosenColor
    }
 
 
 // Creating convenience init - using it is not compulsory when creating an object
    
    convenience init(customerChosenColor : String) {
        self.init()
        color = customerChosenColor
    }
}

Creating a method for the class

enum CarType {
    
    case Sedan
    case Coupe
    case Hatchback
    
}



class Car {
    
    
    var color = "Black"
    var numberOfSeats : Int = 5
    

    
    var typeOfCar : CarType = .Coupe
    
    
  
    
    init(customerChosenColor : String) {
        color = customerChosenColor
    }
 

    
    convenience init(customerChosenColor : String) {
        self.init()
        color = customerChosenColor
    }

// Method created 
    
    func drive() {
        print("car is moving.")
    }
    
    
}

 

Creating the Object

// Creating a new object

let myCar = Car()
let richGuysCars = Car(customerChosenColor: "Red")

// Printing properties of the class

print(myCar.color)
print(myCar.numberOfSeats)
print(myCar.typeOfCar)


// method drive is only associated with myCar Object

myCar.drive()

 

Inheritance : Class – In Swift

// Class inherit. SelfDrive class inherits the Car class and the method in the class car called drive()

class SelfDrive : Car {
    
    var destination : String = "Apple Store"
    
    override func drive() {

// super.drive() means adding the default functionality to the override being performed.
        super.drive()
        
        print("Driving to " + destination)
    }
    
}

 

 

Prateek Katyal

Prateek Katyal

I create ‘stuff’ on the interwebs ? ‘Stuff’ ? photos, videos, websites ?

Leave a Reply