Add



Swift Classes

In Swift, you write classes with the keyword "class". Class supports inheritance i.e. one class can be inherited from other class. To access current instance, "self" keyword is used. For example, in the example, self.calcName has been used in init method.

Initializer

Initializers are written with init name. It can have different number of parameters. It is used to initialize the instance. Note that unlike Structure there is no by default init written. You have to write init even if you need init without parameter.

De-initializer

De-initializer is written with deinit name. In it, clean up code is normally written.

    class OmerJavedCalculator
    {
	    // Instance Property
	    var calcName : String	
	    // Type Property
	    static var location : String = "London"
	    // Initializer
	    init(calcName: String)
	    {
		    self. calcName = calcName
        }
        // Instance Method
        func multiplyTwoNumbers(firstNum: Int, secondNum: Int) -> Int
        {
	        return  firstNum * secondNum
        }
        // Type Method
        static func addTwoNumbers(firstNum: Int, secondNum: Int) -> Int
        {
	        return  firstNum + secondNum
        }

        // De-initializer
        deinit
        {
	        // Clean up code goes here
        }
    }

Instance Creation

To make an instance of class OmerJavedCalculator, we will write Initializer’s parameters with class name. For example,

    var calculator = OmerJavedCalculator(calcName:"Omer’s Calculator")

Instance Method

    print(calculator.multiplyTwoNumbers(3,6))

It will print 18.

Type Method

A Type method is written with the static keyword. It is accessed with the class name. If some type method is to be overridden in the subclass then instead of static, class keyword can be written.

    class MyClass
    {
	    class func myTypeMethod()
	    {
		    print (“I am a type method”);
        }
    }

MyClass. myTypeMethod() is the way to access it.

To call addTwoNumbers method with the class name as this is the type method.

    print(OmerJavedCalculator.addTwoNumbers(4,5))

It will print 9.

Inheritance

One class can be inherited from other class. Inheritance is done by writing first child class name then base class name separated by colon.

    class MyBaseClass
    {
	    ...
    }
    class MyChildClass : MyBaseClass
    {
	    ...
    }

Child class inherits properties and methods from its base class. Moreover, child class can override these things as well. To override, “override” keyword is used.

Preventing Overrides

You can use "final" keyword to prevent a method, property, or subscript from being overridden.