In this post, we will see how to manage Class in swift.
CLASS DEFINITION
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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:
1 2 3 4 5 6 7 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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:
