Category Archives: Swift Tutorial

Swift Tutorial

Swift Deinitialization

Swift Deinitialization

Swift is smart enough at memory management, it automatically deallocates an instance and free up occupied resources when instance is no longer needed. Deinitialization is the process which deallocate or freeup occupied memory and other system resource for an instance no longer in use.

In swift, we have special method called deinitializer that can take care of whole deinitialization process. Deinitializer are invoked immediately before a class instance is deallocated.

In swift, an deinitializer can be created by implementing deinit() method with zero parameters, there can be only one deinitializer per class.

Swift Deinitialization Syntax

Following is the syntax of an deinitializer , an instance method with no parameters is created with the deinit keyword.

Syntax:-

Example:-

Output:-

swift_deinitializer

Swift Initialization

Swift Initialization

When an instance of a class, structure, or enumeration is created it must be provided with some initial values before it is ready to be used. Instance initialization is the process which involves setting up initial value for instance property and to perform any required task to make instance ready to use.

In swift, we have special method called initializers that can take care of whole initialization process. Initializers are invoked automatically when an instance of a particular is created. The Initializers ensure that new instances of a type created is correctly initialized before they are used for the first time.

In swift, an intializer can be created by implementing init() method with zero more parameters, initializers does not mean to return any value.

Swift Initializer Syntax

Syntax:-

Following is the simplest form of an initializer, an instance method with no parameters is created with the init keyword.

Example:-

Here, we have defined a class with two(radius and area) properties and defined a initializer init() method. For radius we have assigned initial value during its declaration and we have calculated area value in initializer init() method, and there is instance method getArea return area value when invoked.

When you run above swift program you will see the following output –

Output:-

swift_initializers

Swift Initialization with Parameters

In swift, an intializer init() method is allowed to accept zero more parameters. An intializer init() method with zero more parameters can be defined as following –

Syntax:-

Example:-

Output:-

swift_initializer_with_parameters

Swift Initialization with Multiple Initializers

In swift, we are allowed define multiple initializer init() methods, initializer is executed based on argument list.

Example:-

Output:-

swift_initialization_with_multiple_initializers

Swift Initializer with Parameter Names and Argument Labels

In swift, we are allowed define multiple initializer init() methods. In an initializer parameter names are used to refer parameters internally while argument labels are used when initializer is called. As all the initializers are defined with the same name init, then only way to identify which initializer to be executed is argument list. An initializer is invoked based on the number of arguments, name of arguments or type of arguments.

Initializer Parameters Without Argument Labels

If you want to ignore argument labels in initializer parameters, then you can use underscore (_) instead of an external argument label before particular parameter name.

Swift Optional Property Types

In swift, if we have properties with optional type, those properties are automatically initialized with nil or no value during initialization.

Default Initializers

In swift, class or structure is provided with a default initializer which allows it to set default values for all of its properties. The default initializer creates an instance for class or structure itself that sets default values of its properties.

Example:-

Output:-

swift_default_initializer

 

Swift Initializer Delegation for Value Types

Initializer delegation is a process in which an intializer is allowed to call another initializers to perform part of an instance’s initialization. Initializer delegation helps to avoid duplicate code across multiple initializers. Initializer delegation works in differently for value types and class types.

 

Initializer Inheritance and Overriding

In swift a subclasses is not allowed to inherit their superclass initializers by default. If a subclass initializer matches a superclass designated initializer, this way you are providing an override for superclass designated initializer. Therefore, you are required to add override modifier before the subclass’s initializer definition, this is applicable even if you are overriding an automatically provided default initializer.Conversely, if a subclass initializer matches a superclass convenience initializer, you are not required to write override modifier when providing a matching
implementation of a superclass convenience initializer.

Swift Failable Initializer

In swift a class, structure or enumeration initializer may fail for any of the following reason –

  • Invalid initialization parameter values
  • Absence of required external sources
  • Conditions that prevents initializer to succeed

In swift a Failable Initializer allow us to catch and notify initializer method exceptions. The failable initializer can be defined by placing question mark after the init keyword (init?). The failable initializer creates an optional value for the type it is initialized, here a return statement with nil value is used to indicate initialization failure.

Example:-

Output:-

swift_failable_initializer

The init! Failable Initializer

The failable initializer created with question mark after init keyword (init?) creates an optional instance of the respective type. In swift there is an alternate way you can create failable initializer by placing an exclamation mark after the init keyword (init!), this way an implicitly unwrapped optional instance is created.

Example:-

Here, we have defined a super class “EmpInfo” and sub class “SalaryInfo” with failable initializers to catch exceptions in super and sub classes. As we discussed if one initializer fail, the entire program stops execution immediately.

When we run the above swift program, we see the following output –

Output:-

swift__init_failable_initializer_with_exclamation

Required Initializers

In swift, initializer with required modifier is termed as “Required Initializer“, it tells compiler that we must implement the initializer method in all sub classes.

Example:-

Output:-

swift_required_initializer

Swift Inheritance

Swift Inheritance

The inheritance is one of the important feature in object oriented programming, that facilitates the code reusability. Inheritance is a mechanism through which a class(derived class) can inherit properties and methods from an existing class(base class).

Sub Class:- The class that inherits properties and methods from another class is know as Sub-class or Derived-Class.

Super Class:- The class whose properties and methods are being inherited by sub class is called Base Class or Super class.

Swift Base Class

The class whose properties and methods are being inherited by sub class is called Base Class or Super class.In swift any class that is not being inherit from any other class is known as a base class.In swift, there is no universal base class, any classes you define without specifying a superclass automatically become base classes.

In Swift, class can be defined using the class keyword as following –

Syntax:-

Here, className is replaced with the actual class name then in between the curly brackets {} we define all the associated class properties and methods.

Example:-

Output:-

swift_inheritance_baseclass

Swift Sub Class

The class that inherits properties and methods from another class is known as Sub-class or Derived-Class.In swift subclass are also allowed to override the properties or methods of base class. In addition to the inherited properties and methods a sub class can also have their own properties and methods.

In swift, a subclass can be defined using subclass name before the superclass name, separated by a colon.

Syntax:-

Example:-

Output:-

swift_inheritance_subclass

Swift Overriding

In swift, a subclass is allowed to customize an instance method, type method, instance property, type property, or subscript as per requirement, this feature is known as overriding in swift.

Swift Method Overriding

We have seen using inheritance method defined in a baseclass is inherited by its subclass and is used by subclass instances. However, we may want an instance to respond behave differently for the same method defined in baseclass. This can be achieved by method overriding. In method overriding we are allowed to define a method in subclass with same name, parameter list and return type. Then, when that method is called, method defined in the subclass is invoked instead of the one defined in the baseclass.

In swift, a baseclass methods can be overridden in subclass by the “override” keyword followed by method definition with same name, parameter list and return type as in baseclass.

Example:-

Output:-

swift_method_overriding

Swift Overriding Properties

Inherited properties of a baseclass can be overridden in subclass to provide own custom getter and setter for that specific property, or to add property observers to overriding property to observe when that property value changes.

Example:-

Output:-

swift_overriding_properties

Swift Overriding Property Observers

In swift, property observer can be added to an inherited property as property overriding. Adding property observer allows us to be notified when the value of an inherited property changes.

Example:-

Output:-

swift_overriding_property_observer

Swift Prevent Overriding

In swift, all of the methods and properties can be overridden in subclass by default. If we want to prevent a method, property, or subscript from being overridden in subclasses, we can declare them as final using final keyword. Making a method or property final ensures that they won’t be altered in subclasses. Similarly if we want to prevent a class being inherited or subclassed further then we can make it final using final keyword.

Swift Subscripts

Swift Subscripts

In Swift, subscripts are used to retrieve any specific information from a collection, list, or sequence without using a method. With the help of subscripts we can store and retrieve the values directly using associated index.

Defining Subscripts In Swift

In swift, general syntax to declare a subscript is very similar with syntax to declare instance method and computed property. You need use subscript keyword followed by parameter list and a return type, in the subscript body there is a getter and a setter properties to define whether subscript is a read-write or ready-only.

Syntax:-

Syntax for read only:-

Example:-

Output:-

swift_subscript_readonly

Example:-

Output:-

swift_subscript

Swift Subscripts Options

Subscripts are allowed to take one or more parameters of any data type and subscripts does not support default parameter values.In swift we can provide multiple subscripts for a class or structure based on requirement, it is known as “subscript overloading”.

Example:-

Output:-

swift_subscript_options

Swift Methods

Swift Methods

In Swift, methods are actually functions associated with classes, structures, and enumerations.Methods describes the behavior for a instance of a classes, structures, or enumerations and mean to provide specific functionality to that type instance and operates on its properties. In swift following two type of methods available –

  1. Instance Methods
  2. Type Methods

Swift Instance Methods

Instance methods are associated with the instances of a specific class, structure, or enumeration. Instance methods are used to perform certain functionality or task for those instances.Instance methods can be invoked using the instance of that type. In swift, instance method can be defined same way as function.

Syntax:-

func :- It is swift a keyword which is used to define a function.
fun_name :- It is replaced with the name of the function .
parameter_list :- It represents the list of the parameters need to be passed when function call made.
return_type :- It represents return type of the function.

Once an instance method is defined it can be invoked using the instance of that class, structure, or enumeration.

Example:-

Output:-

swift_class_access_property_method

Swift Self-Property in Methods

Every instance in swift has an implicit property that refer the current instance within its own instance methods.This implicit property is called as “self” and it is exactly equivalent to the current instance itself.Self property allow us to refer any property or method for the current instance using self keyword followed by dot(.) operator and then property name as following –

Syntax for Property:-

Syntax for Method:-

Example:-

Output:-

swift_access_property_using_self

Swift Modify Value Types from Instance Methods

In swift properties of a structures and enumerations type cannot be modified from within its instance methods because structures and enumerations are value type.

However, if you want to allow structure or enumeration properties to be modified from within its instance method then it can be achieved by opting in for this behavior by placing the mutating keyword before the func keyword for that method.

Example:-

Output:-

swift_modify_value_type

Swift Self Property for Mutating Method

In swift we can assign an entirely new instance to the implicit self property inside a mutating method.

Example:-

Output:-

swift_self_property_mutating_method

Swift Type Methods

Instance methods are called on an instance of a particular type. In swift, we are allowed to define type method that can be called on the type itself.Type methods can be created using static keyword before the a method’s func keyword. Type method can be invoked using dot syntax(.) with the type itself instead if instance.

Example:-

Output:-

swift_type_method

 

Swift Properties

Swift Properties

Properties is way to associate an attribute and its value with a particular class, structure, or enumeration.Properties can be a constant or variable that stores associated values for classes, structures or enumerations. In swift, properties have getter and setter methods to set, modify or retrieve property value.

In Swift, properties can classified into following two types –

  1. Stored properties
  2. Computed properties

Swift Stored Properties

The stored properties are simply a constant or variable that is being associated and stored as part of an instance of any specific class or structure. The stored properties can be a variable or constant stored properties that can be declared using var or let keyword with an initial value.

Example:-

Output:-

swift_stored_properties

Swift Lazy Stored Properties

In Swift we have a flexible property type called as lazy stored properties whose initial values is not evaluated until it is accessed or used for the first time. Lazy stored properties are useful when we want to hold initialization for some complex computations or when initial value of property to dependent upon some external factors. In swift a property can be declared as lazy stored property using lazy keyword just before its declaration.

Example:-

Output:-

swift_lazy_stored_properties

 

Swift Computed Properties

In swift unlike stored properties computed properties calculates value at the run time rather than to store.Computed properties have a getter to retrieve the value and an optional setter to initialize values.Computed properties can be defined for classes, structures, and enumerations whereas stored properties are defined for classes and structures.

Computed properties can also be declared using var keyword, but rather than an initial value we assign a function to calculate the value.

Example:-

Output:-

swift_computed_properties

Swift Read-Only Computed Properties

The Read-Only computed property are computed property with only getter but no setter. Read-Only computed property are always mean to return a value and can be accessed through dot (.) syntax.

Example:-

Output:-

swift_read_only_computed_properties

Swift Property Observer

In swift property observers observe and responds to changes in a property’s value. Property observer is invoked every time property’s value changes or set to new value, even if the new values is same as current value.Property observers can be added to any stored properties except lazy stored properties, it can also be added to any inherited property by overriding the property within a subclass.

In swift, we have following two types of observers.

  • willSet – It is called just before the value is stored.
  • didSet – It is called after a new value is stored.

Example:-

Output:-

swift_property_observer

Swift Type Property

In Swift, Instance properties are associated with individual instance of a class or structure. Every a new instance created it has separate copy of property values from other instances.In Swift, we can define a special kind of properties that is associated to the class or structure itself, rather than any individual instance no matter how many instances have been created, there will always one copy of these properties will available for all instances of that type.These properties are termed as type properties.Type properties can be defined using ‘static‘ keyword and for class types ‘class‘ keyword is used.

Example:-

Output:-

swift_type_properties

Swift Classes

Swift Classes

Class can be defined as a blueprint or prototype of associated objects. Class wrapper that binds the data and methods which can be later accessed by objects of that class. We can think of a class as a user-defined data type, that describes the behavior and characteristics shared by all of its instances.

Defining a Class In Swift

In Swift, class can be defined using the class keyword as following –

Syntax:-

Here, className is replaced with the actual class name then in between the curly brackets {} we define all the associated class properties and methods.

Example:-

Swift Class Instances

Once a class has been defined, we can create instance or objects of that class which has access to class properties and methods. In swift, an instance of a class can be created as following –

Syntax:-

Here, objectName and className is replaced with actual object name and the class name respectively.

Example:-

Output:-

swift_class_objects

Swift Accessing Instance variable and methods

In swift once we have got an instance of a class created, we can access properties and method of that class using property/method name separated by a dot (.) operator after the instance name as following.

Syntax for Property:-

Syntax for Method:-

Example:-

Output:-

swift_class_access_property_method

 

Swift Class Identity Operators

In swift class instances are of the reference types, which means all of the class objects shares memory reference to the class store instead of having an copy of class. There may be possibilities that multiple constants and variables will refer the same class instance.

In Swift, we have a set of identity operators allow us to check two constants and variables referring to same instance of a class or not.

Operator Description
Identical Operator(===) It returns true when two constants or variables pointing to a same instance
Not Identical Operator used is (!==) It returns true when two constants or variables pointing to a different instance

Example:-

Output:-

swift_class_identical_operators

Swift Classes are Reference Type

In swift class are of the reference types, which means when we assign it to any constants, variables or function reference to same existing instance will be used instead of an individual value copy of class.

Example:-

Here, in the above example we defined a class employee, we created an instance emp1 with initial value “Alex” for empName property, then we have created another instance emp2 by assigning it previous instance emp1 and updated the value of empName property for emp2 instance, now we printed the value of empName property for both the instances and see the value is updated for both the instance because class are reference type and both instances having reference to the same class instance.

Output:-

swift_class_are_reference_type

 

Swift Higher Order functions

Swift Higher Order functions

In Swift, higher order function is simply a function that either takes a function as an argument, or returns a function. In swift array type has some important higher order functions.

Map –

It loop over the elements in a collection and applies the same operation to each of the element in collection. It returns an array containing result after applying required operation on collection elements.

Example:-

Output:-

swift_higher_order_map

Filter –

It loops over array elements and returns an array contains only elements that satisfy filter specified in your closure.

Example:-

Output:-

swift_higher_order_function_filter

Reduce –

The reduce function combine all items in a collection to create a single new value. The Reduce function takes two parameters, an initial value of the result and a closure which takes two arguments, one is the initial value or the result from the previous execution of the closure and the other one is the next item in the collection.

Example:-

Here, the initial value ($0) will be 0 and then the value from nums array is added to the initial value, which is retained for next iteration. In the end, one single value is returned

Output:-

swift_higher_order_function_reduce

Swift Structures

Swift Structures

Structure is a user-defined data type, that encapsulate the properties (variables and constant) and methods(functions). It is named type, you can define and five it a name and later you can use it in your. In Swift, Classes and structures are much similar, but one key differences is that classes are reference and structures are value types.

Unlike many other programming languages where structure are mostly used to group related data together, swift structures are fully feature rich and you are allowed to do following things only possible with class –

properties
instance methods
type methods
initializers
subscripts
extensions
protocols

Defining a Structure In Swift

In Swift, structure can be defined using the struct keyword as following –

Syntax:-

Here, structName is replaced with the actual structure name then in between the curly brackets {} we define all the properties and methods associated with the structure.

Example:-

Swift Structure Instances

Once a structure has been defined, we can create instance or objects of that structure which has access to structure properties and methods. In swift, an instance of a structure can be created as following –

Syntax:-

Here, instName and structName is replaced with actual instance name and the structure name respectively.

Example:-

Output:-

swift_structure_instance

Swift Accessing Instance variable and methods

In swift once we have got an instance of a structure created, we can access properties and method of that structure using property/method name separated by a dot (.) operator after the instance name as following.

Syntax for Property:-

Syntax for Method:-

Example:-

Output:-

swift_structure_access_instance_property_method

Swift Structure Initializers

An initializer is a special kind of function in swift, it is used to provide initial values to structure properties while an instance of structure is created.

Example:-

Output:-

swift_structure_initializers

Swift Structures are Value Type

In swift class are of the value types, which means when we assign it to any constants, variables or function an individual copy of structure is created for each of the instance.

Example:-

Here, in the above example we defined a structure employee, we created an instance emp1 with initial value “Alex” for empName property, then we have created another instance emp2 by assigning it previous instance emp1 and updated the value of empName property for emp2 instance, now we printed the value of empName property for both the instances and see that both the instance having individual copy of property.

Output:-

swift_structures_are_value_type

Difference between Classes and Structures

  • Main difference between a class and structure is that classes are reference type and structures are value types.
  • Structures does not provide deinitializers
  • Structures does not provide default mutation
  • Structures does not support type casting

 

 

Swift Variadic Function

Swift Variadic Function

A variadic function is a function that can accept variable number of arguments. In Swift, when are you not sure about the input parameter for a function then you have option to create a A variadic function. A variadic function allows us to You can pass zero or more parameters for a function. A variadic function can be declare using an ellipsis/three dots after type of parameter.

Example:-

Output:-

swift_variadic_function

Swift Enumerations

Swift Enumerations

An Enumeration is a first-class data type in swift.It is consist of a set of predefined named values, called as members. Enumerations are useful when we want deal with limited set of values for variable. For example you can think of the colors of a traffic light can only be one of three colors– red, yellow or green.

Swift enumerations are much powerful yet flexible, we can access its values in a type-safe manner within your code. Enumeration values can be a string, a character, or a value of any integer or floating-point type.

Defining an enumeration

In Swift, enumeration can be declared using the enum keyword followed by a list of the individual members introduced between curly brackets {} using the case keyword.

Syntax:-

Example:-

Let’s define an enumeration for days of week –

Dot syntax

Dot syntax can be used to refer enumeration’s member if the type of an enumeration is known or can be inferred.

Example:-

Output:-

swift_enum_dot_syntax

Swift Enumeration with Switch Statement

In Swift, an enumeration can be used in switch statement as following –

Example:-

Output:-

swift_switch_with_enumeration

Swift Enumeration with Raw Values

In Swift Enumeration members can be associated with a prepopulated raw value of type Int, String, Character, etc. All of the enum member should have raw values of same type and must be unique.If integers are used for raw values, they auto-increment if no value is specified for any members.

Example:-

Output:-

swift_enum_raw_value

Swift Enumeration with Associated Values

In associated values we can store data with member of an enumeration, which changes between different instances of an enumeration. With associated values you can associate a tuple with multiple to a member of enumerations, this tuple can be of different type for each of the enumeration members.

Example:-

Output:-

swift_enum_associted_value

Iterating over Enumeration Cases

In swift, it is possible to iterate over the enumeration cases, for this we have to enable this property by adding CaseIterable after the enumeration name, then swift exposes a collection of all the cases in an allCases property of the enumeration type.Once all set, we can loop through the enum members using for-in loop as following –

Example:-

Output:-

Note:- Above Syntax must comply with the CaseIterable protocol.

Recursive Enumerations

An enumeration with another instance of the enumeration as the associated value for one or more of the enumeration is termed as recursive enumeration.A indirect keyword is used to indicate that enumeration is a recursive.

Example:-

Output:-

swift_recursive_enueration