Thursday, October 8, 2015

Swift Learning - classes and initializers

class Shape
{
var numberOfSide = 0

init(name:String)
{
self.name = name
}

func simpleDescription() -> String 
{
return “A shape with number of sides \(numberOfSide)”
}
}

to create an instance of the class, just put a parentheses 

var shapeObj = Shape()
shapeObj.numberOfSides = 10
var shapeDescription = shapeObj.simpleDescription()

init is called to specify the initializer. 

var shapeObj = Shape(name:”SmpleShape”)

Like other programming languages, here also we have inheritence concept A class can only inherit from one class. 
Application can use the the override keyword to override a method. If did not use, the compiler will give error. 

There is a concept called fail able initilizer, which is represented by init? fail-able initializer can return nil after initialization. 

e.g. 

class Circle:NamedShape
{
var radius : Double

init?(radius:Double, name:String)
{
self.radius = radius
super.init(name:name)
if (radius < 0 )
{
return nil
}
}
}

A designated initializer indicates that its one of the primary initializers of a class. any initializer within a class must ultimately call through to a designated initializer. A convenience initializer is a secondary initializer which adds additional behavior for customization, but ultimately should go through the designated initializer. designated and convenience keywords are used for indicating this respectively. 

A required keyword next to an initializer indicates that every subclass of the class that has initializer must implement its own version of the initializer. 

type casting is a way to check the type of instance and to treat that instance as if it is a different superclass or subclass somewhere else in its own hierarchy. 

A constant or a variable of a certain type may actually refer to an instance of subclass behind the scenes. If this is the case, using the typecast operator, we can downcast to that type. 

Because down casting can fail, the type cast operator comes in two forms. as? gives an optional value of the type to which it is attempted to down cast to. as! downcasts and also force unrwaps the result as a single compound action. 

as? to be used when we are not sure the downcast will succeed. as! to be used if we are sure the downcast will succeed. 

e.g. is like below 

if let triangle = shape as Triangle 
{
triangle++
}

References:

No comments:

Post a Comment