{"id":795,"date":"2022-07-24T06:20:13","date_gmt":"2022-09-28T16:36:18","guid":{"rendered":"https:\/\/www.silicloud.com\/blog\/uncategorized\/swifts-init\/"},"modified":"2024-03-07T14:38:57","modified_gmt":"2024-03-07T14:38:57","slug":"init-or-swift-initialization-in-swift","status":"publish","type":"post","link":"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/","title":{"rendered":"init or Swift initialization in Swift"},"content":{"rendered":"<p>In this Swift tutorial, we will be focusing on a crucial concept known as Swift init or Swift initialization. The process of initialization occurs when we generate an instance of a certain type.<\/p>\n<h2>Initialize a <a href=\"https:\/\/www.swift.com\/homepage\">Swift<\/a> object.<\/h2>\n<p>Initialization is the act of getting a class, structure, or enumeration ready to be used by setting an initial value for each stored property and performing any necessary setup or initialization before the instance can be used.<\/p>\n<p>In Java programming, constructors and initializers function in a similar manner. Due to Swift&#8217;s type-safe nature, there are numerous rules that govern how initializers are implemented. Unless you have a solid understanding of the concept, it can be challenging to successfully execute them.<\/p>\n<h3>The syntax for initializing in Swift.<\/h3>\n<pre class=\"post-pre\"><code>init() {\r\n    \/\/ initialise the stored properties here.\r\n}\r\n<\/code><\/pre>\n<p>Below is an example class for us to examine.<\/p>\n<pre class=\"post-pre\"><code>class A{\r\n    \r\n    \/\/Compilation error. No initializer is defined.\r\n    var a : Int\r\n    var b : String\r\n    var c : Int?\r\n    let website = \"SC\"\r\n}\r\n<\/code><\/pre>\n<p>The class mentioned will not compile because the Swift compiler raises an error regarding the uninitialized stored properties. It is not possible to keep stored properties in an uncertain state. Therefore, we are left with two potential choices.<\/p>\n<ol>\n<li style=\"list-style-type: none;\">\n<ol>You can set a default value for a property directly in its definition.<\/ol>\n<\/li>\n<\/ol>\n<p>&nbsp;<\/p>\n<ol>To initialize properties, employ an initializer called init().<\/ol>\n<p>We will examine each of the approaches individually.<\/p>\n<pre class=\"post-pre\"><code>class A{\r\n    \r\n    var a : Int = 5\r\n    var b : String = \"Hello. How you're doing\"\r\n    var c : Int?\r\n    let website = \"SC\"\r\n}\r\n<\/code><\/pre>\n<p>Once the stored properties have been assigned default values, Swift automatically provides a default initializer. After initializing the class instance, all properties and functions can be accessed using the dot operator.<\/p>\n<pre class=\"post-pre\"><code>var object = A()\r\nobject.a = 10\r\nobject.c = 2\r\n<\/code><\/pre>\n<p>One option for paraphrasing the sentence natively could be:<\/p>\n<p>You can also initialize the stored properties by utilizing the init() method demonstrated in the example below.<\/p>\n<pre class=\"post-pre\"><code>class A{\r\n    \r\n    var a : Int\r\n    var b : String\r\n    var c : Int?\r\n    let website = \"SC\"\r\n    \r\n    init(a: Int, b: String) {\r\n        self.a = a\r\n        self.b = b\r\n    }\r\n}\r\n\r\nvar object = A(a: 5, b: \"Hello World\")\r\n<\/code><\/pre>\n<p>The Swift Optional type does not require initialization since it is not a stored property. Stored properties, on the other hand, can be accessed using the self property within the init() method. It is important to note that self is used to refer to the current instance within its own instance methods, similar to how &#8220;this&#8221; is used in Java. The initializer mentioned above is the main initializer of the class and is also known as the designated initializer. It is worth mentioning that initializers allow us to modify constant properties as well.<\/p>\n<pre class=\"post-pre\"><code>class A{\r\n    \r\n    var a : Int\r\n    var b : String\r\n    var c : Int?\r\n    let website : String\r\n    \r\n    init(a: Int, b: String, website: String) {\r\n        self.a = a\r\n        self.b = b\r\n        self.website = website\r\n    }\r\n}\r\n\r\nvar object = A(a: 5,b: \"Hello World\", website: \"SC\")\r\n<\/code><\/pre>\n<h3>Memberwise initializers for structures can be paraphrased as initializers that initialize the members of a structure individually.<\/h3>\n<p>Value types like structures do not always need a defined initializer. By default, structures automatically receive a memberwise initializer, unless custom initializer(s) have been defined. Below are examples of code snippets that demonstrate different ways to initialize a structure.<\/p>\n<pre class=\"post-pre\"><code>struct Rect{\r\n    var length : Int\r\n    var breadth : Int\r\n}\r\nvar r = Rect(length: 5, breadth: 10)\r\n<\/code><\/pre>\n<pre class=\"post-pre\"><code>struct Rect{\r\n    var length : Int = 5\r\n    var breadth : Int = 10\r\n}\r\n\r\nvar r = Rect()\r\nvar r1 = Rect(length: 10, breadth: 5)\r\n<\/code><\/pre>\n<p>Because we have set default values for the stored properties in the code above, we now have a default initializer without any member initialization in addition to the memberwise initializer.<\/p>\n<pre class=\"post-pre\"><code>struct Rect{\r\n    var length : Int\r\n    var breadth : Int\r\n    \r\n    init(length: Int, breadth: Int) {\r\n        self.length =  length + 10\r\n        self.breadth = breadth + 10\r\n    }\r\n}\r\nvar r = Rect(length: 10, breadth: 5)\r\n<\/code><\/pre>\n<p>In the given scenario, we have created our own custom initializer. If we don&#8217;t need an external name for the initializer, we can indicate it by using an underscore &#8216;_&#8217; as shown below.<\/p>\n<pre class=\"post-pre\"><code>class A{\r\n    \r\n    var a : Int\r\n    var b : String\r\n    var c : Int?\r\n    let website = \"SC\"\r\n    \r\n    init(_ a: Int, _ b: String) {\r\n        self.a = a\r\n        self.b = b\r\n    }\r\n}\r\n\r\nvar object = A(5,\"Hello World\")\r\n<\/code><\/pre>\n<pre class=\"post-pre\"><code>struct Rect{\r\n    var length : Int\r\n    var breadth : Int\r\n    \r\n    init(_ length: Int, _ breadth: Int) {\r\n        self.length =  length + 10\r\n        self.breadth = breadth + 10\r\n    }\r\n}\r\nvar r = Rect(10, 10)\r\n<\/code><\/pre>\n<h3>Different Types of Initializers in Swift<\/h3>\n<p>There are several types of class initializers that can be broadly categorized as follows:<\/p>\n<ol>\n<li style=\"list-style-type: none;\">\n<ol>Primary initializers, also known as designated initializers, are responsible for fully initializing all properties introduced by their class before calling any superclass initializer. It is possible for a class to have multiple designated initializers, but at least one is required for every class.<\/ol>\n<\/li>\n<\/ol>\n<p>On the other hand, secondary initializers called convenience initializers, provide additional initialization options for a class. They must call a designated initializer of the same class. Convenience initializers are not mandatory and can be used for custom setups. They have the same syntax as primary initializers, but with the convenience modifier placed before the init keyword.<\/p>\n<pre class=\"post-pre\"><code>class Student{\r\n    \r\n    var name : String\r\n    var degree : String\r\n    \r\n    init(name : String, degree: String) {\r\n        self.name = name\r\n        self.degree = degree\r\n    }\r\n    \r\n    convenience init()\r\n    {\r\n        self.init(name: \"Unnamed\", degree: \"Computer Science\")\r\n    }\r\n    \r\n}\r\nvar student = Student()\r\nstudent.degree \/\/ \"Computer Science\"\r\nstudent.name \/\/ \"Unnamed\"\r\n<\/code><\/pre>\n<p>Convenience initializers are beneficial for automatically assigning default values to stored properties.<\/p>\n<h3>Initializer delegation for value types in Swift.<\/h3>\n<p>You can avoid repeating code by calling one initializer from another. Structures, which are value types, do not have inheritance capabilities. So, the only way to call an initializer within the same structure is through this method. An example is provided below.<\/p>\n<pre class=\"post-pre\"><code>struct Rect{\r\n    var length : Int\r\n    var breadth : Int\r\n    \r\n    init(_ length: Int, _ breadth: Int) {\r\n        self.length =  length\r\n        self.breadth = breadth\r\n    }\r\n    \r\n    init(_ length: Int)\r\n    {\r\n        self.init(length, length)\r\n    }\r\n}\r\nvar r = Rect(10, 5)\r\nvar r1 = Rect(15) \/\/initialises the length and breadth to 15\r\n<\/code><\/pre>\n<h3>Initializer Delegation in Swift for Reference Types.<\/h3>\n<p>Since classes are reference types, they can inherit from other classes and their initializers can also call initializers from the superclass. This allows for the proper inheritance and initialization of all values. The following rules are defined to handle relationships between initializers.<\/p>\n<ul class=\"post-ul\">\n<li>A designated initializer must call a designated initializer from its immediate superclass.<\/li>\n<li>A convenience initializer must call another initializer from the same class.<\/li>\n<li>A convenience initializer must ultimately call a designated initializer.<\/li>\n<\/ul>\n<p>The above rules are depicted in the following illustration.<\/p>\n<div><img decoding=\"async\" class=\"post-images\" title=\"\" src=\"https:\/\/cdn.silicloud.com\/blog-img\/blog\/img\/655cca4cc40ba52feef282a3\/39-0.png\" alt=\"swift init, swift initialization delegation flow\" \/><\/div>\n<p>In a subclass, convenience initializers cannot use the super keyword and must delegate across, while designated initializers must always delegate up.<\/p>\n<h3>Inheriting and overriding Swift initializers.<\/h3>\n<p>By default, subclasses in Swift do not automatically inherit initializers from their superclass unless specific criteria are fulfilled (Automatic Initializer Inheritance). This approach is implemented to avoid incomplete initialization in subclasses. Now, let&#8217;s examine the functionality of designated and convenience initializers in the context of inheritance. To begin with, we will establish a base class called Vehicle, which will serve as the foundation for the subclasses. The classes will utilize Enums as a data type. Here is the definition of our Vehicle base class:<\/p>\n<pre class=\"post-pre\"><code>enum VehicleType : String {\r\n    case twoWheeler = \"TwoWheeler\"\r\n    case fourWheeler = \"FourWheeler\"\r\n}\r\n\r\nclass Vehicle{\r\n    \r\n    var vehicleType : VehicleType\r\n    \r\n    init(vehicleType: VehicleType) {\r\n        self.vehicleType = vehicleType\r\n        print(\"Class Vehicle. vehicleType is \\(self.vehicleType.rawValue)\\n\")\r\n    }\r\n    \r\n    convenience init()\r\n    {\r\n        self.init(vehicleType: .fourWheeler)\r\n    }\r\n}\r\n\r\nvar v = Vehicle(vehicleType: .twoWheeler)\r\n<\/code><\/pre>\n<p>Please note that the convenience initializer needs to call the designated initializer of the same class by using self.init. Now, we will create a subclass of the class mentioned above, following the example below.<\/p>\n<pre class=\"post-pre\"><code>enum TwoWheelerType : String\r\n{\r\n    case scooty = \"Scooty\"\r\n    case bike = \"Bike\"\r\n}\r\n\r\nclass TwoWheeler : Vehicle{\r\n    \r\n    var twoWheelerType : TwoWheelerType\r\n    var manufacturer : String\r\n    \r\n    init(twoWheelerType : TwoWheelerType, manufacturer : String, vType : VehicleType) {\r\n        self.twoWheelerType = twoWheelerType\r\n        self.manufacturer = manufacturer\r\n        print(\"Class TwoWheeler. \\(self.twoWheelerType.rawValue) manufacturer is \\(self.manufacturer)\")\r\n        super.init(vehicleType: vType)\r\n        \r\n    }\r\n}\r\n<\/code><\/pre>\n<p>Key points to take into consideration:<\/p>\n<ul class=\"post-ul\">\n<li>The designated initializer of the subclass must initialize its own properties before calling the designated initializer of the superclass.<\/li>\n<li>A subclass can modify inherited properties of the superclass only after the super.init is called.<\/li>\n<\/ul>\n<p>The code provided would result in a compile-time error.<\/p>\n<pre class=\"post-pre\"><code>class TwoWheeler : Vehicle{\r\n    \r\n    var twoWheelerType : TwoWheelerType\r\n    var manufacturer : String\r\n    \r\n    init(twoWheelerType : TwoWheelerType, manufacturer : String, vType : VehicleType) {\r\n        self.twoWheelerType = twoWheelerType\r\n        self.manufacturer = manufacturer\r\n        self.vehicleType = vType \/\/Won't compile\r\n        super.init(vehicleType: vType)\r\n        \/\/self.vehicleType = .fourWheeler \/\/This would work.\r\n        \r\n    }\r\n}\r\n\r\nvar t = TwoWheeler(twoWheelerType: .scooty, manufacturer: \"Hero Honda\", vType: .twoWheeler)\r\n<\/code><\/pre>\n<p>As mentioned before, the subclass does not automatically inherit the superclass initializer. Therefore, the initialization below would not be successful.<\/p>\n<pre class=\"post-pre\"><code>var t = TwoWheeler(vehicleType: .twoWheeler) \/\/manufacturer property isn't initialized.\r\n<\/code><\/pre>\n<p>In order to override an initializer, the subclass initializer needs to be identical to the superclass&#8217;s designated initializer. In such a situation, the override keyword is added to the initializer.<\/p>\n<pre class=\"post-pre\"><code>class TwoWheeler : Vehicle{\r\n    \r\n    var twoWheelerType : TwoWheelerType\r\n    var manufacturer : String\r\n    \r\n    init(twoWheelerType : TwoWheelerType, manufacturer : String, vType : VehicleType) {\r\n        self.twoWheelerType = twoWheelerType\r\n        self.manufacturer = manufacturer\r\n        print(\"Class TwoWheeler. \\(self.twoWheelerType.rawValue) manufacturer is \\(self.manufacturer)\")\r\n        super.init(vehicleType: vType)\r\n        \r\n    }\r\n    \r\n    override init(vehicleType: VehicleType)\r\n    {\r\n        print(\"Class TwoWheeler. Overriden Initializer. \\(vehicleType.rawValue)\")\r\n        self.twoWheelerType = .bike\r\n        self.manufacturer = \"Not defined\"\r\n        super.init(vehicleType: vehicleType)\r\n    }\r\n\r\n\r\n\r\n<\/code><\/pre>\n<p>The initializer below does not override the one from the superclass because it has a different parameter name.<\/p>\n<pre class=\"post-pre\"><code>\/\/This would give a compile-time error since the parameter v doesn't match with the superclass.\r\noverride init(v: VehicleType)\r\n    {\r\n        self.twoWheelerType = .bike\r\n        self.manufacturer = \"Not defined\"\r\n        super.init(vehicleType: v)\r\n    }\r\n<\/code><\/pre>\n<p>Using a convenience initializer to override the superclass&#8217;s initializer.<\/p>\n<pre class=\"post-pre\"><code>class TwoWheeler : Vehicle{\r\n    \r\n    var twoWheelerType : TwoWheelerType\r\n    var manufacturer : String\r\n    \r\n    init(twoWheelerType : TwoWheelerType, manufacturer : String, vType : VehicleType) {\r\n        self.twoWheelerType = twoWheelerType\r\n        self.manufacturer = manufacturer\r\n        print(\"Class TwoWheeler. \\(self.twoWheelerType.rawValue) manufacturer is \\(self.manufacturer)\")\r\n        super.init(vehicleType: vType)\r\n        \r\n    }\r\n    \r\n    override convenience init(vehicleType: VehicleType) {\r\n        self.init(twoWheelerType: .bike, manufacturer: \"Not Defined\", vType: .twoWheeler)\r\n        self.vehicleType = vehicleType\r\n    }\r\n}\r\nvar t = TwoWheeler(twoWheelerType: .scooty, manufacturer: \"Hero Honda\", vType: .twoWheeler)\r\nt = TwoWheeler(vehicleType: .twoWheeler)\r\n\r\n\/\/Output\r\nFollowing gets printed on the console:\r\nClass TwoWheeler. Scooty manufacturer is Hero Honda\r\nClass Vehicle. vehicleType is TwoWheeler\r\n\r\nClass TwoWheeler. Bike manufacturer is Not Defined\r\nClass Vehicle. vehicleType is TwoWheeler\r\n\r\n<\/code><\/pre>\n<p>The override keyword is added to the convenience initializer, which then calls the designated initializer within the same class. It should be noted that the order of the keywords convenience and override is not important.<\/p>\n<h3>Necessary initializers.<\/h3>\n<p>To ensure that each subclass implements a specific initializer, it is necessary to add the keyword &#8220;required&#8221; before the initializer. Furthermore, this &#8220;required&#8221; modifier must also be included in the corresponding subclass implementations. Here is an example demonstrating the use of Required Initializers on the mentioned classes.<\/p>\n<pre class=\"post-pre\"><code>class Vehicle{\r\n    \r\n    var vehicleType : VehicleType\r\n    \r\n    required init(vehicleType: VehicleType) {\r\n        self.vehicleType = vehicleType\r\n        print(\"Class Vehicle. vehicleType is \\(self.vehicleType.rawValue)\\n\")\r\n    }\r\n    \r\n    convenience init()\r\n    {\r\n        self.init(vehicleType: .fourWheeler)\r\n    }\r\n}\r\n\r\nclass TwoWheeler : Vehicle{\r\n    \r\n    var twoWheelerType : TwoWheelerType\r\n    var manufacturer : String\r\n    \r\n    init(twoWheelerType : TwoWheelerType, manufacturer : String, vType : VehicleType) {\r\n        self.twoWheelerType = twoWheelerType\r\n        self.manufacturer = manufacturer\r\n        print(\"Class TwoWheeler. \\(self.twoWheelerType.rawValue) manufacturer is \\(self.manufacturer)\")\r\n        super.init(vehicleType: vType)\r\n        \r\n    }\r\n    \r\n     required init(vehicleType: VehicleType) {\r\n        self.manufacturer = \"Not Defined\"\r\n        self.twoWheelerType = .bike\r\n        super.init(vehicleType: vehicleType)\r\n    }\r\n}\r\n<\/code><\/pre>\n<p>Please note that by adding a required modifier, the initializer will be overridden, allowing the override keyword to be omitted. The usage of a required initializer, along with convenience required and convenience initializers, is separate and can be combined. To illustrate this, we will create another subclass of Vehicle.<\/p>\n<pre class=\"post-pre\"><code>enum FourWheelerType : String\r\n{\r\n    case car = \"Car\"\r\n    case bus = \"Bus\"\r\n    case truck = \"Truck\"\r\n}\r\n\r\n\r\nclass FourWheeler : Vehicle\r\n{\r\n    var fourWheelerType : FourWheelerType\r\n    var name : String\r\n    \r\n    init(fourWheelerType : FourWheelerType, name: String, vehicleType: VehicleType) {\r\n        self.fourWheelerType = fourWheelerType\r\n        self.name = name\r\n        print(\"Class FourWheeler. \\(self.fourWheelerType.rawValue) Model is \\(self.name)\")\r\n        super.init(vehicleType: vehicleType)\r\n        self.vehicleType = vehicleType\r\n    }\r\n    \r\n    required convenience init(vehicleType: VehicleType) {\r\n        self.init(fourWheelerType: .bus, name: \"Mercedes\", vehicleType: vehicleType)\r\n    }\r\n}\r\n\r\n\r\nclass Car : FourWheeler{\r\n    \r\n    var model : String\r\n    \r\n    init(model: String) {\r\n        self.model = model\r\n        print(\"Class Car. Model is \\(self.model)\")\r\n        super.init(fourWheelerType: .car, name: self.model, vehicleType: .fourWheeler)\r\n    }\r\n    \r\n    required init(vehicleType: VehicleType)\r\n    {\r\n        self.model = \"Not defined\"\r\n        print(\"Class Car. Model is \\(self.model)\")\r\n        super.init(fourWheelerType: .car, name: self.model, vehicleType: vehicleType)\r\n    }\r\n    \r\n}\r\n<\/code><\/pre>\n<p>Key points to consider in the given code excerpt:<\/p>\n<ul class=\"post-ul\">\n<li>Convenience initializers are secondary initializers in a class.<\/li>\n<li>Setting a convenience initializer as required means that implementing it in the subclass is compulsory.<\/li>\n<\/ul>\n<h3>Inheritance of Automatic Initializers<\/h3>\n<p>A subclass automatically inherits the initializers from the superclass in two different scenarios.<\/p>\n<ul class=\"post-ul\">\n<li>Don\u2019t define any designated initializers in your subclass.<\/li>\n<li>Implement all the designated initializers of the superclass. All the convenience initializers would be automatically inherited too.<\/li>\n<\/ul>\n<p>The snippet below exemplifies the first rule in action.<\/p>\n<pre class=\"post-pre\"><code>class Name {\r\n    \r\n    var name: String\r\n    \r\n    init(n: String) {\r\n        self.name = n\r\n    }\r\n}\r\n\r\nclass Tutorial: Name {\r\n    \r\n    var tutorial : String? = \"Swift Initialization\"\r\n}\r\n\r\nvar parentObject = Name(n: \"Anupam\")\r\nvar childObject = Tutorial(n: \"SC\")\r\n<\/code><\/pre>\n<p>The snippet below demonstrates the second rule in action.<\/p>\n<pre class=\"post-pre\"><code>class Name {\r\n    \r\n    var name: String\r\n    \r\n    init(n: String) {\r\n        self.name = n\r\n    }\r\n    \r\n    convenience init()\r\n    {\r\n        self.init(n: \"No name assigned\")\r\n    }\r\n}\r\n\r\nclass Tutorial: Name {\r\n    \r\n    var tutorial : String? = \"Swift Tutorial\"\r\n    \r\n    override init(n : String) {\r\n        super.init(n: n)\r\n    }\r\n}\r\n\r\nvar parentObject = Name(n: \"Anupam\")\r\nvar childObject = Tutorial(n: \"SC\")\r\nvar childObject2 = Tutorial()\r\nprint(childObject2.name) \/\/prints \"No name assigned\r\n<\/code><\/pre>\n<p>In the above code, the subclass can automatically access the convenience initializer of the superclass.<\/p>\n<h3>Failable Initializer in Swift<\/h3>\n<p>Failable initializers can be defined using the keyword init? on Classes, Structures, or Enumerations. These initializers are called when the initialization process fails due to reasons such as invalid parameter values or absence of an external source. By creating an optional value of the initialized type, a failable initializer can trigger an initialization failure by returning nil, even though an init method doesn&#8217;t technically return anything. Failable Initializers are applicable to Structures as well.<\/p>\n<pre class=\"post-pre\"><code>struct SName {\r\n    let name: String\r\n    init?(name: String) {\r\n        if name.isEmpty { return nil }\r\n        self.name = name\r\n    }\r\n}\r\n\r\nvar name = SName(name: \"SC\")\r\nif name != nil {\r\n    print(\"init success\") \/\/this gets displayed\r\n}\r\nelse{\r\n    print(\"init failed\")\r\n}\r\nname  = SName(name: \"\")\r\n\r\nif name != nil {\r\n    print(\"init success\")\r\n}\r\nelse{\r\n    print(\"init failed\") \/\/this gets displayed\r\n}\r\n\r\n<\/code><\/pre>\n<p>Enums that can have initializers that can potentially fail.<\/p>\n<pre class=\"post-pre\"><code>enum CharacterExists {\r\n    case A, B\r\n    init?(symbol: Character) {\r\n        switch symbol {\r\n        case \"A\":\r\n            self = .A\r\n        case \"B\":\r\n            self = .B\r\n        default:\r\n            return nil\r\n        }\r\n    }\r\n}\r\n\r\n\r\nlet ch = CharacterExists(symbol: \"C\")\r\nif ch != nil {\r\n    print(\"Init failed. Character doesn't exist\")\r\n}\r\n<\/code><\/pre>\n<pre class=\"post-pre\"><code>class CName {\r\n    let name: String\r\n    init?(name: String) {\r\n        if name.isEmpty { return nil }\r\n        self.name = name\r\n    }\r\n}\r\nvar name  = CName(name: \"\")\r\n\r\nif name != nil {\r\n    print(\"init success\")\r\n}\r\nelse{\r\n    print(\"init failed\")\r\n}\r\n<\/code><\/pre>\n<p>Please note that it is not possible for a failable initializer and a non-failable initializer to share the same parameter types and names.<\/p>\n<h3>Replacing a Failable Initializer<\/h3>\n<p>In your subclass, it is possible to replace a failable initializer with a non-failable initializer, but the reverse is not allowed. Below is an example demonstrating the override of a failable initializer with a non-failable initializer.<\/p>\n<pre class=\"post-pre\"><code>class CName {\r\n    let name: String\r\n    init?(name: String) {\r\n        if name.isEmpty { return nil }\r\n        self.name = name\r\n    }\r\n}\r\nvar name  = CName(name: \"\")\r\n\r\nclass SubName : CName{\r\n    \r\n    var age : Int\r\n    override init(name: String)\r\n    {\r\n        self.age = 23\r\n        super.init(name: name)!  \r\n    }\r\n}\r\n<\/code><\/pre>\n<p>Forced unwrapping is employed to invoke a failable initializer from the superclass while implementing a nonfailable initializer in a subclass. This concludes the Swift initialization tutorial, with references from Apple Docs.<\/p>\n<p>&nbsp;<\/p>\n<p>More Tutorials<\/p>\n<p><a class=\"LinkSuggestion__Link-sc-1gewdgc-4 cLBplk\" href=\"https:\/\/www.silicloud.com\/blog\/ios-progress-bar-also-known-as-progress-view\/\" target=\"_blank\" rel=\"noopener\">Progress Bar iOS also known as Progress View<span class=\"sc-gswNZR eASTkv\">(Opens in a new browser tab)<\/span><\/a><\/p>\n<p><a class=\"LinkSuggestion__Link-sc-1gewdgc-4 cLBplk\" href=\"https:\/\/www.silicloud.com\/blog\/set-in-python\/\" target=\"_blank\" rel=\"noopener\">Set in Python<span class=\"sc-gswNZR eASTkv\">(Opens in a new browser tab)<\/span><\/a><\/p>\n<p><a class=\"LinkSuggestion__Link-sc-1gewdgc-4 cLBplk\" href=\"https:\/\/www.silicloud.com\/blog\/java-string-substring-method\/\" target=\"_blank\" rel=\"noopener\">Java String substring() method<span class=\"sc-gswNZR eASTkv\">(Opens in a new browser tab)<\/span><\/a><\/p>\n<p><a class=\"LinkSuggestion__Link-sc-1gewdgc-4 cLBplk\" href=\"https:\/\/www.silicloud.com\/blog\/substring-in-python-refers-to-extracting-a-smaller-portion-of-a-string\/\" target=\"_blank\" rel=\"noopener\">Python Substring refers to extracting a smaller portion of a string.<span class=\"sc-gswNZR eASTkv\">(Opens in a new browser tab)<\/span><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this Swift tutorial, we will be focusing on a crucial concept known as Swift init or Swift initialization. The process of initialization occurs when we generate an instance of a certain type. Initialize a Swift object. Initialization is the act of getting a class, structure, or enumeration ready to be used by setting an [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[],"class_list":["post-795","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v21.5 (Yoast SEO v21.5) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>init or Swift initialization in Swift - Blog - Silicon Cloud<\/title>\n<meta name=\"description\" content=\"we will be focusing on a crucial concept known as Swift init or Swift initialization. The process of initialization occurs when we generate\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"init or Swift initialization in Swift\" \/>\n<meta property=\"og:description\" content=\"we will be focusing on a crucial concept known as Swift init or Swift initialization. The process of initialization occurs when we generate\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/\" \/>\n<meta property=\"og:site_name\" content=\"Blog - Silicon Cloud\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/SiliCloudGlobal\/\" \/>\n<meta property=\"article:published_time\" content=\"2022-09-28T16:36:18+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-03-07T14:38:57+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/cdn.silicloud.com\/blog-img\/blog\/img\/655cca4cc40ba52feef282a3\/39-0.png\" \/>\n<meta name=\"author\" content=\"Benjamin Taylor\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@SiliCloudGlobal\" \/>\n<meta name=\"twitter:site\" content=\"@SiliCloudGlobal\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Benjamin Taylor\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/\"},\"author\":{\"name\":\"Benjamin Taylor\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/#\/schema\/person\/ac801fe9549a25960ce48aa2e0a691c9\"},\"headline\":\"init or Swift initialization in Swift\",\"datePublished\":\"2022-09-28T16:36:18+00:00\",\"dateModified\":\"2024-03-07T14:38:57+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/\"},\"wordCount\":1498,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.silicloud.com\/blog\/#organization\"},\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/\",\"url\":\"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/\",\"name\":\"init or Swift initialization in Swift - Blog - Silicon Cloud\",\"isPartOf\":{\"@id\":\"https:\/\/www.silicloud.com\/blog\/#website\"},\"datePublished\":\"2022-09-28T16:36:18+00:00\",\"dateModified\":\"2024-03-07T14:38:57+00:00\",\"description\":\"we will be focusing on a crucial concept known as Swift init or Swift initialization. The process of initialization occurs when we generate\",\"breadcrumb\":{\"@id\":\"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.silicloud.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"init or Swift initialization in Swift\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/#website\",\"url\":\"https:\/\/www.silicloud.com\/blog\/\",\"name\":\"Silicon Cloud Blog\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/www.silicloud.com\/blog\/#organization\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/#organization\",\"name\":\"Silicon Cloud Blog\",\"url\":\"https:\/\/www.silicloud.com\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.silicloud.com\/blog\/wp-content\/uploads\/2023\/11\/EN-SILICON-Full.png\",\"contentUrl\":\"https:\/\/www.silicloud.com\/blog\/wp-content\/uploads\/2023\/11\/EN-SILICON-Full.png\",\"width\":1024,\"height\":1024,\"caption\":\"Silicon Cloud Blog\"},\"image\":{\"@id\":\"https:\/\/www.silicloud.com\/blog\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/SiliCloudGlobal\/\",\"https:\/\/twitter.com\/SiliCloudGlobal\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/#\/schema\/person\/ac801fe9549a25960ce48aa2e0a691c9\",\"name\":\"Benjamin Taylor\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.silicloud.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/ec2e3d3e2d525fd148047c4520ae7c1cdccd1f4b48a1a488422b31f04f345c14?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/ec2e3d3e2d525fd148047c4520ae7c1cdccd1f4b48a1a488422b31f04f345c14?s=96&d=mm&r=g\",\"caption\":\"Benjamin Taylor\"},\"url\":\"https:\/\/www.silicloud.com\/blog\/author\/benjamintaylor\/\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"init or Swift initialization in Swift - Blog - Silicon Cloud","description":"we will be focusing on a crucial concept known as Swift init or Swift initialization. The process of initialization occurs when we generate","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/","og_locale":"en_US","og_type":"article","og_title":"init or Swift initialization in Swift","og_description":"we will be focusing on a crucial concept known as Swift init or Swift initialization. The process of initialization occurs when we generate","og_url":"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/","og_site_name":"Blog - Silicon Cloud","article_publisher":"https:\/\/www.facebook.com\/SiliCloudGlobal\/","article_published_time":"2022-09-28T16:36:18+00:00","article_modified_time":"2024-03-07T14:38:57+00:00","og_image":[{"url":"https:\/\/cdn.silicloud.com\/blog-img\/blog\/img\/655cca4cc40ba52feef282a3\/39-0.png"}],"author":"Benjamin Taylor","twitter_card":"summary_large_image","twitter_creator":"@SiliCloudGlobal","twitter_site":"@SiliCloudGlobal","twitter_misc":{"Written by":"Benjamin Taylor","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/#article","isPartOf":{"@id":"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/"},"author":{"name":"Benjamin Taylor","@id":"https:\/\/www.silicloud.com\/blog\/#\/schema\/person\/ac801fe9549a25960ce48aa2e0a691c9"},"headline":"init or Swift initialization in Swift","datePublished":"2022-09-28T16:36:18+00:00","dateModified":"2024-03-07T14:38:57+00:00","mainEntityOfPage":{"@id":"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/"},"wordCount":1498,"commentCount":0,"publisher":{"@id":"https:\/\/www.silicloud.com\/blog\/#organization"},"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/","url":"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/","name":"init or Swift initialization in Swift - Blog - Silicon Cloud","isPartOf":{"@id":"https:\/\/www.silicloud.com\/blog\/#website"},"datePublished":"2022-09-28T16:36:18+00:00","dateModified":"2024-03-07T14:38:57+00:00","description":"we will be focusing on a crucial concept known as Swift init or Swift initialization. The process of initialization occurs when we generate","breadcrumb":{"@id":"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.silicloud.com\/blog\/init-or-swift-initialization-in-swift\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.silicloud.com\/blog\/"},{"@type":"ListItem","position":2,"name":"init or Swift initialization in Swift"}]},{"@type":"WebSite","@id":"https:\/\/www.silicloud.com\/blog\/#website","url":"https:\/\/www.silicloud.com\/blog\/","name":"Silicon Cloud Blog","description":"","publisher":{"@id":"https:\/\/www.silicloud.com\/blog\/#organization"},"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.silicloud.com\/blog\/#organization","name":"Silicon Cloud Blog","url":"https:\/\/www.silicloud.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.silicloud.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/www.silicloud.com\/blog\/wp-content\/uploads\/2023\/11\/EN-SILICON-Full.png","contentUrl":"https:\/\/www.silicloud.com\/blog\/wp-content\/uploads\/2023\/11\/EN-SILICON-Full.png","width":1024,"height":1024,"caption":"Silicon Cloud Blog"},"image":{"@id":"https:\/\/www.silicloud.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/SiliCloudGlobal\/","https:\/\/twitter.com\/SiliCloudGlobal"]},{"@type":"Person","@id":"https:\/\/www.silicloud.com\/blog\/#\/schema\/person\/ac801fe9549a25960ce48aa2e0a691c9","name":"Benjamin Taylor","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.silicloud.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/ec2e3d3e2d525fd148047c4520ae7c1cdccd1f4b48a1a488422b31f04f345c14?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/ec2e3d3e2d525fd148047c4520ae7c1cdccd1f4b48a1a488422b31f04f345c14?s=96&d=mm&r=g","caption":"Benjamin Taylor"},"url":"https:\/\/www.silicloud.com\/blog\/author\/benjamintaylor\/"}]}},"_links":{"self":[{"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/posts\/795","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/comments?post=795"}],"version-history":[{"count":4,"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/posts\/795\/revisions"}],"predecessor-version":[{"id":1783,"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/posts\/795\/revisions\/1783"}],"wp:attachment":[{"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/media?parent=795"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/categories?post=795"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.silicloud.com\/blog\/wp-json\/wp\/v2\/tags?post=795"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}