Swift Tutorial - Tutorialspoint

(backadmin) #1
println("result is: \(result.studname)")

println("result is: \(result.stmark)")

println("result is: \(result.pass)")

When we run above program using playground, we get following result.


result is: nil
result is: 98
result is: true

The above program is defined with class name as 'defaultexample'. Three member
functions are initialized by default as 'studname?' to store 'nil' values, 'stmark' as 98 and
'pass' as Boolean value 'true'. Likewise the member values in the class can be initialized
as default before processing the class member types.


Memberwise Initializers for Structure Types


When the custom initializers are not provided by the user, Structure types in Swift will
automatically receive the 'memberwise initializer'. Its main function is to initialize the new
structure instances with the default memberwise initialize and then the new instance
properties are passed to the memberwise initialize by name.


struct Rectangle {
var length = 100.0, breadth = 200.0
}
let area = Rectangle(length: 24.0, breadth: 32.0)

println("Area of rectangle is: \(area.length)")
println("Area of rectangle is: \(area.breadth)")

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


Area of rectangle is: 24.0
Area of rectangle is: 32.0

Structures are initialized by default for their membership functions during initialization for
'length' as '100.0' and 'breadth' as '200.0'. But the values are overridden during the
processing of variables length and breadth as 24.0 and 32.0.


Initializer Delegation for Value Types


Initializer Delegation is defined as calling initializers from other initializers. Its main
function is to act as reusability to avoid code duplication across multiple initializers.

Free download pdf