Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Syntax:
2.
Initializer Role for Stored Properties
2.1.
Setting Property Values by Default
2.2.
Parameter Initialization
2.3.
Local and external variables
3.
Class Inheritance and Initialization
3.1.
Designated Initializers
3.1.1.
Syntax:
3.2.
Convenience Initializers
3.2.1.
Syntax:
4.
Initializer Inheritance and Overriding
5.
Failable Initializer
5.1.
Example
6.
Frequently Asked Questions
6.1.
In Swift, what is initialization?
6.2.
In Swift, how do you start a model?
6.3.
Why is initialization required in Swift?
6.4.
In Swift, how do you create a struct?
7.
Conclusion
Last Updated: Mar 27, 2024

Swift Initialization

Author Mayank Goyal
0 upvote

Introduction

Preparing structure, an instance of a class, or enumeration for use is known as initialization. Setting an initial value for each stored attribute on that instance and any other setup or initialization required before the new instance is available for use is part of this procedure.

Initializers, which are special methods that may be called to produce a new instance of a certain type, are used to accomplish this initialization process. Swift initializers do not return a value, unlike Objective-C initializers. Their main responsibility is to guarantee that new instances of a type are properly initialized before being used for the first time.

Class instances can additionally implement a deinitializer, which performs any custom cleanup shortly before the class instance is deallocated.

Syntax:

Swift uses the init() method to create an initializer. For example,

class Example {
  ...


  // create an initializer 
  init() {
    // perform initialization
    ... 
  }
}

Recommended Topic, procedure call in compiler design

Initializer Role for Stored Properties

Before processing the instances, the stored property must first initialize the instances for their classes and structures. The initializer is used to assign and initialize values in stored properties, eliminating the requirement for property observers. A stored property uses an initializer.

  • To establish an initial value.
  • Within the property definition, set the default property value.
  • 'init()' is used to create a specific data type instance. The init() function does not take any arguments.

Setting Property Values by Default

The Init() function in Swift 4 initializes the stored property values. Additionally, while declaring class or structure members, the user has the option of defaulting property values. When a property has the same value throughout the program, rather than initializing it in init, we can declare it in the declaration section (). When inheritance is defined for classes or structures, setting property values by default enables the user.

struct rectangle {
   var length = 6
   var breadth = 12
}


var peri = rectangle()
print("perimeter of rectangle is \(peri.length*peri.breadth)")

The values are initialized directly in the declaration rather than expressing length and width in init().

Parameter Initialization

The user can use the init function in Swift 4 to initialize parameters as part of the initializer's declaration ().

struct Rectangle {
   var length: Double
   var breadth: Double
   var area: Double
   
   init(fromLength length: Double, fromBreadth breadth: Double) {
      self.length = length
      self.breadth = breadth
      area = length * breadth
   }
}
let ar = Rectangle(fromLength: 6, fromBreadth: 12)
print("area is: \(ar.area)")

Local and external variables

Similar to function and method parameters, initialization parameters have local and global parameter names. External parameter declaration is used to invoke the initializer, and local parameter declaration is used to access the initialized body. In contrast to function and method initializers, Swift 4 initializers do not specify which initializer is used to invoke which functions.

Swift 4 adds an automatic external name to each parameter in the init function (). This automatic external name is the same as the local name supplied before each initialization parameter.

Class Inheritance and Initialization

During startup, all of a class's stored properties, including any properties inherited from its superclass, must be given an initial value.

To ensure that all stored properties receive an initial value, Swift defines two types of initializers for class types. Designated initializers and convenience initializers are two types of initializers.

Designated Initializers

The primary initializers for a class are designated initializers. A specified initializer fully initializes all properties introduced by that class before calling an appropriate superclass initializer to continue the process up the superclass chain.

Classes often have a small number of designated initializers, with many having only one. Designated initializers are "funnel" sites where initialization occurs and where the initialization process proceeds up the superclass chain.

At least one designated initializer is required for each class. This criterion can be achieved in some situations by inheriting one or more designated initializers from a superclass.

We write the designated initializers for classes in the same way as simple initializers for value types:

Syntax:

init(parameters) {

   statements

}

Convenience Initializers

Convenience initializers are the class's secondary, supporting initializers. You can use a convenience initializer to call a specified initializer from the same class, with few of the designated initializer's parameters set to default values. We may also build an instance of that class using a convenience initializer for a specific use case or input value type.

If your class doesn't require convenience initializers, you don't have to give them. We can create convenience initializers whenever a shortcut to a common initialization pattern saves time or makes the class's initialization explicit.

Syntax:

convenience init(parameters) {

   statements

}

Initializer Inheritance and Overriding

Swift 4 does not enable subclasses to inherit their superclass's member type initializers by default. Inheritance is only partially relevant to Superclass initializers, as detailed in Automatic Initializer Inheritance.

When the user requires initializers in the superclass, the user must specify a subclass with initializers as a custom implementation. The 'override' keyword must be declared when a subclass must override a superclass.

class sides {
   var corners = 4
   var description: String {
      return "\(corners) sides"
   }
}


let square = sides()
print("Square: \(square.description)")


class pentagon: sides {
   override init() {
      super.init()
      corners = 5
   }
}


let bicycle = pentagon()
print("Pentagon: \(bicycle.description)")

Failable Initializer

The user must be told when an initializer fails while defining a class, structure, or enumeration value. Because of this, the initialization of variables can sometimes fail.

  • Parameter values are incorrect.
  • There is no external source required.
  • Initialization is prevented due to a condition.

Swift 4 introduces a configurable initializer called 'failable initializer' to capture exceptions thrown by initialization methods and warn the concerned user if something goes wrong while initializing structure, class, or enumeration elements. The keyword 'init?' is used to catch the failable initializer. Also, parameter types and names for failable and non-failable initializers cannot be the same.

Example

class File {


  var folder: String


  // failable initializer
  init?(folder: String) {


    // check if empty
    if folder.isEmpty {
      print("Folder Could Not Be Found")
      return nil
    }
    self.folder = folder
  }
}


// create folder1 object
var file = File(folder: "")
if (file != nil) {
  print("File Found Successfully")
}
else {
  print("Error In Finding File")
}

In the preceding example, we developed the failable initializer init?() with a parameter named folder. We've also used the if statement as well as the isEmpty attribute.

if (folder.isEmpty) {return nil} checks whether the folder is empty and returns nil if it is. We gave an empty string "" to the folder1 object, which causes an initialization failure, so the line inside it is executed first, and then it returns nil. The statement inside the else block is then executed.

Frequently Asked Questions

In Swift, what is initialization?

An initializer is a type of function that is used to construct a class or struct object. We use the init() method to create an initializer in Swift.

In Swift, how do you start a model?

To establish a starting point. Set the default property value within the property definition. 'init()' is used to create an instance of a specific data type. The init() function does not take any arguments.

Why is initialization required in Swift?

Swift initialization () The process of preparing an instance of a class, structure, or enumeration for use is known as initialization. Setting an initial value for each stored property on that instance and any other setup or initialization required before the new instance is available for use is part of this procedure.

In Swift, how do you create a struct?

You don't need to write the init method to initialize a struct in Swift. This is because the job is done behind the scenes by a memberwise initializer by default. String as a name? Let name: String? struct Fruit { let name: String? }

Conclusion

Let us brief out the article. 

In this article, we first learned about the role of initializers and the different types of initializers. We are moving on to how a designated and convenience initializer works. That's all from the article. I hope you all like it.

I hope you all like this article. Want to learn more about Data Analysis? A few excellent courses can guide you in your learning process. You can also refer to our other courses like DSA and Machine Learning.

Happy Learning, Ninjas!

Live masterclass