Javatpoint Logo
Javatpoint Logo

Swift4 Initialization

Swift Classes, structures and enumerations are used for preparing instance of a class once declared in Swift4. Initial value is initialized for stored property. The values are initialized to proceed further. The 'init()' method is used to create initialization function. Swift 4 initializer is different from Objective-C as it does not return any values. Its function is to check for initialization of newly created instances before its processing. Swift 4 also provides 'deinitialization' process for performing memory management operations once the instances are deallocated.

Initializer for Stored Properties

Stored properties have to initialize the instances for their classes and structures before processing the instances. Stored properties use initializer to assign and initialize values without need to call property observers.

  • To create an initial value.
  • To assign default property value within the property definition.
  • To initialize an instance for a particular data type 'init()' is used. No arguments are passed inside the init() function.

Syntax:

Example

Output:

volume of cube is 288.0 

Here,

  • The structure "cube" is initialized with member length, breadth and height as "Double" datatype.
  • Init() method is used to initialize the values for the newly created members.
  • Volume of cube is calculated and returned by calling the cube function.

Setting Property Values by Default

In Swift4 programming language, the init() function is used 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.

Example:

Output:

volume of cube is 288

Parameter Initialization

In Swift4 language, the user can initialize parameters as part of the initializer's definition using init().

Example:

Output:

area is: 72.0
area is: 432.0

Next TopicSwift Typecasting





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA