Swift – Class (Part I)

By | 14/10/2019

In this post, we will see how to manage Class in swift.

CLASS DEFINITION

import UIKit

// [Class definition]
class User{
    // property
    var Name:String
    var YearBirth:Int
     
    // Constructor
    init(inputName:String, inputYearBirth: Int) {
        Name = inputName
        YearBirth = inputYearBirth
    }
     
    // Function used to calcolate the Age
    func CalculateAge() -> Int {
        let date = Date()
        let calendar = Calendar.current
        let components = calendar.dateComponents([.year], from: date)
        return (components.year! - YearBirth)
    }
}



CREATION AN INSTANCE OF USER CLASS:

let objUser = User(inputName: "Damiano", inputYearBirth: 1974)

print("Class User")
print("Function used: CalculateAge")
// Call the function to calcolate the Age
print("My age is: \(objUser.CalculateAge())")
print("")



DEFINITION OF OPERATOR CLASS THAT INHERITS FROM USER:

class Operator:User
{
    var Office:String
    // Constructor
    init(Name:String, YearBirth: Int, InputOffice: String) {
        Office = InputOffice
        // User's Constructor
        super.init(inputName: Name, inputYearBirth: YearBirth)
    }
     
    func PrintInfo() {
        print("My Name is \(Name), age \(CalculateAge()) and I work in \(Office)")
    }
}
 
// Create an instance of Operator class
let objOperator = Operator(Name: "Damiano", YearBirth: 1974, InputOffice: "London")

print("Class Operator")
print("Function used: PrintInfo")
// Call the function PrintInfo
objOperator.PrintInfo()

// Call the function CalculateAge
print("Function used: CalculateAge")
print("My age is: \(objOperator.CalculateAge())")



If we run this code in Playground, this will be the result:



Leave a Reply

Your email address will not be published. Required fields are marked *