Swift Tutorial - Tutorialspoint

(backadmin) #1
println("area of rectangle is \(area.length*area.breadth)")

When we run the above program using playground, we get the following result:


area of rectangle is 72.0

Here the structure 'rectangle' is initialized with members length and breadth as 'Double'
datatypes. Init() method is used to initialize the values for the newly created members
length and double. Area of rectangle is calculated and returned by calling the rectangle
function.


Setting Property Values by Default


Swift language provides Init() function to initialize the stored property values. Also, the
user has provision to initialize the property values by default while declaring the class or
structure members. When the property takes the same value alone throughout the
program we can declare it in the declaration section alone rather than initializing it in init().
Setting property values by default enables the user when inheritance is defined for classes
or structures.


struct rectangle {
var length = 6
var breadth = 12
}
var area = rectangle()
println("area of rectangle is \(area.length*area.breadth)")

When we run the above program using playground, we get the following result:


area of rectangle is 72.0

Here instead of declaring length and breadth in init() the values are initialized in
declaration itself.


Parameters Initialization


In Swift language the user has the provision to initialize parameters as part of the
initializer's definition using init().


struct Rectangle {
var length: Double
var breadth: Double
var area: Double

init(fromLength length: Double, fromBreadth breadth: Double) {
Free download pdf