Sunday 27 November 2016

Decorator Design Pattern In Swift

Decorator Design Pattern:

This pattern allows behavior to be added to an individual object either statically or dynamically, without affecting the behavior of other objects from the same class.The decorator pattern is used to extend or alter the functionality of objects at run- time by wrapping them in an object of a decorator class. This provides a flexible alternative to using inheritance to modify behaviour.


protocol Coffee {
    func getCost() -> Double
    func getIngredients() -> String
}

class SimpleCoffee: Coffee {
    func getCost() -> Double {
        return 1.0
    }

    func getIngredients() -> String {
        return "Coffee"
    }
}

class CoffeeDecorator: Coffee {
    private let decoratedCoffee: Coffee
    private let ingredientSeparator: String = ", "

    required init(decoratedCoffee: Coffee) {
        self.decoratedCoffee = decoratedCoffee
    }

    func getCost() -> Double {
        return decoratedCoffee.getCost()
    }

    func getIngredients() -> String {
        return decoratedCoffee.getIngredients()
    }
}

class Milk: CoffeeDecorator {
    required init(decoratedCoffee: Coffee) {
        super.init(decoratedCoffee: decoratedCoffee)
    }

    override func getCost() -> Double {
        return super.getCost() + 0.5
    }

    override func getIngredients() -> String {
        return super.getIngredients() + ingredientSeparator + "Milk"
    }
}

class WhipCoffee: CoffeeDecorator {
    required init(decoratedCoffee: Coffee) {
        super.init(decoratedCoffee: decoratedCoffee)
    }

    override func getCost() -> Double {
        return super.getCost() + 0.7
    }

    override func getIngredients() -> String {
        return super.getIngredients() + ingredientSeparator + "Whip"
    }
}


var someCoffee: Coffee = SimpleCoffee()
print("Cost : \(someCoffee.getCost()); Ingredients: \(someCoffee.getIngredients())")
someCoffee = Milk(decoratedCoffee: someCoffee)
print("Cost : \(someCoffee.getCost()); Ingredients: \(someCoffee.getIngredients())")
someCoffee = WhipCoffee(decoratedCoffee: someCoffee)
print("Cost : \(someCoffee.getCost()); Ingredients: \(someCoffee.getIngredients())")
Output
Cost : 1.0; Ingredients: Coffee
Cost : 1.5; Ingredients: Coffee, Milk

Cost : 2.2; Ingredients: Coffee, Milk, Whip

Thursday 24 November 2016

Composite Pattern In Swift

Today we learn about composite pattern used in swift. Lets start.
The composite pattern describes that a group of objects is to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.The composite pattern is used to create hierarchical, recursive tree structures of related objects.

When to use :
Composite should be used when clients ignore the difference between compositions of objects and individual objects. If programmers find that they are using multiple objects in the same way, and often have nearly identical code to handle each of them, then composite is a good choice; it is less complex in this situation to treat primitives and composites as homogeneous.

Structure Of Composite Pattern:
Component
  • is the abstraction for all components, including composite ones
  • declares the interface for objects in the composition
  • (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate
Leaf
  • represents leaf objects in the composition
  • implements all Component methods
Composite
  • represents a composite Component (component having children)
  • implements methods to manipulate children
  • implements all Component methods, generally by delegating them to its children

Example: 

// Component
protocol Shape {
  func draw(fillColor: String )
}
// Leafs
class Square : Shape{
  func draw(fillColor: String) {
    print("Drawing a Square with color \(fillColor)")

  }
}
class Circle: Shape{
  func draw(fillColor: String) {
    print("Drawing a Circle with color \(fillColor)")

  }
}

// Composite
class Table : Shape{
  lazy var shapes = [Shape]()
  init(_ shapes:Shape...) {
    self.shapes = shapes
  }
  func draw(fillColor: String) {
    for shape in self.shapes{
      shape.draw(fillColor: fillColor)
    }
  }
}
var table = Table(Circle(),Square())
table.draw(fillColor: "Red")

Output:

Drawing a Circle with color Red
Drawing a Square with color Red

Conclusion : 
Today we learn about Composite pattern used in Swift.If you have any questions just leave a comment below and I’ll respond as soon as I can.

Monday 21 November 2016

Adapter Pattern In Swift

Today I will talk about Adapter pattern in swift.What is Adapter pattern and what are its pros and cons.How I will use adapter pattern in my swift code.Lets start now.
When I think about is adapter.Generally it comes to my  mind that adapter is 

a device for connecting pieces of equipment that cannot be connected directly.What in terms of design pattern it can be defined as.

Adapter Design Pattern:
In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code.
Adapter pattern works as a bridge between two  interfaces. This type of design pattern comes under structural pattern as this pattern combines the capability of two independent interfaces.
This pattern involves a single class which is responsible to join functionalities of independent or incompatible interfaces.
Example:
A real life example could be a case of card reader which acts as an adapter between memory card and a laptop. You plugin the memory card into card reader and card reader into the laptop so that memory card can be read via laptop.



Use of Design Pattern:
This pattern is often used when dealing with frameworks, libraries, and APIs to easily "adapt" the old and existing interfaces to the new requirements of a program.

Roles:
The adapter pattern converts the interface of another existing class into an interface waited by the existing clients to allow them to work together. Thanks to this pattern, you can integrate components for which you normally cannot modify the source code and things that often appear with the use of a framework.

The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.

Example:
protocol PersonBioData {
  var fullName: String {get}
  var wholeAddress: String {get}
}
//Adapptee
struct PersonDetails{
  var firstName: String
  var lastName: String
  var pincode: String
  var street : String
  var city : String
  var houseNo : String
  init(firstName:String,lastName:String,pincode:String,street:String,houseNo:String,city:String) {
    self.firstName = firstName
    self.lastName = lastName
    self.pincode = pincode
    self.street = street
    self.houseNo = houseNo
    self.city = city
  }
}

//Adapter
struct EmployeeRecordBook: PersonBioData {
  private let personDetail : PersonDetails
  var fullName: String{
    let fullName = personDetail.firstName + " " + personDetail.lastName
    return fullName
    
  }
  var wholeAddress: String {
   let wholeAddess = personDetail.houseNo+" "+personDetail.street+" "+personDetail.city+" "+personDetail.pincode
    return wholeAddess
  }
  init(personDetail: PersonDetails) {
    self.personDetail = personDetail
  }
}
let personDetails = PersonDetails(firstName: "Ashok", lastName: "Kumar", pincode: "110086", street: "Nehru Road", houseNo: "House # 65", city: "Mumbai")
let employeeRecordBook = EmployeeRecordBook(personDetail: personDetails)
print(employeeRecordBook.fullName)

print(employeeRecordBook.wholeAddress)

Output
Ashok Kumar
House # 65 Nehru Road Mumbai 110086

In this you can see that PersonDetails(adaptee) class is wrapped with EmployeeRecordBook(adapter class). 

Conclusion : 
Today we learn about Adapter pattern used in Swift.If you have any questions just leave a comment below and I’ll respond as soon as I can.


Thursday 17 November 2016

Lazy Stored Property In Swift3.0

Today we learn about lazy stored property in swift.What is lazy stored property and how it works?We also know about its advantage .Lets start with its implementation. 

Lazy Stored Property :
A lazy stored property is a property whose initial value is not calculated until the first time it is used.You indicate a lazy stored property by writing the lazy modifier before its declaration.

Note*You must always declare a lazy property as a variable (with the var keyword), because its initial value might not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.

class Number {
  lazy var value =87
    
  func showNumber() {
    print("My luck number is \(value)")
  }
  
}
let number = Number()
print(number.showNumber())


Here Sample class having lazy stored property named "no".Here instance of Number class is declared as lazy stored property.The lazy keyword makes sure the property is only set if / when showNumber function  it’s called. 

In Swift, you can use a closure  to set the value in  lazy stored property

class Number {
  lazy var value: Int = {
    return 87
  }()
  func showNumber() {
    print("My luck number is \(value)")
  }
  
}
let number = Number()
print(number.showNumber())

Advantage of using lazy stored property:
  1. Lazy properties are useful when the initial value for a property is dependent on outside factors whose values are not known until after an instance’s initialization is complete.
  2. Lazy properties are also useful when the initial value for a property requires complex or computationally expensive setup that should not be performed unless or until it is needed.
  3. Lazy loading is initializing your properties only if / when they are called. This way, memory is not allocated for that property until absolutely necessary, and if the property is actually never used, the memory doesn’t get allocated at all.

Conclusion : Today we studied about lazy stored property in swift. If  you guys any query or concern you can leave your comment.I will  try to reply your query as soon as possible.

Wednesday 16 November 2016

Properties In Swift

Today we learn about  properties used in swift. Properties associate values with a particular class, structure, or enumeration.There are two types of properties used in swift.

  1. Stored Property
  2. Computed Property
Stored Property : 
Stored properties store constant and variable values as part of an instance.Stored properties are provided only by classes and structures.

Computed Property :
Computed properties calculate a value.Computed properties are provided by classes, structures, and enumerations.

Stored and computed properties are usually associated with instances of a particular type. However, properties can also be associated with the type itself. Such properties are known as type properties.

In addition, you can define property observers to monitor changes in a property’s value, which you can respond to with custom actions. Property observers can be added to stored properties you define yourself, and also to properties that a subclass inherits from its superclass.

Example of Stored Property:

struct Person {let name : String
var fullAddress: String
}
let person = Person(name: "Peter", fullAddress: "House # 981 , Mumbai")

Here name and fullAddress is stored property.name is constant stored property while fullAddress is variable stored property.

Stored Properties of Constant Structure Instances :

If you create an instance of a structure and assign that instance to a constant, you cannot modify the instance’s properties, even if they were declared as variable properties.

struct Person {
  let name: String?
  var fullAddress: String?
}
let obj = Person(name: "peter", fullAddress: "mumbai")
obj.fullAddress = "newdelhi"

Error : Cannot assign to property: 'obj' is a 'let' constant.
This is because struct are value type.You have change let to var.Then only it will work.

Stored Properties of Constant Class Instances : If you create an instance of a class and assign that instance to a constant, you  modify the instance’s properties.
class Person1 {
  let name1: String = "ravi"
  var fullAdderess: String = "mumbai"
}
let person1 = Person1()
person1.fullAdderess = "aiims"
print(person1.fullAdderess)

Output: aiims

Here you can see that we making person1 instance as constant and it allows to change the stored property.This is because classes are reference type .You assign an instance of a reference type to a constant, you can still change that instance’s variable properties.

Computed Property 

Classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly. 

Example :

struct Area {
  var width : Double
  var height : Double
  var totalAreas : Double {
    get {
      return width * height
    }
    set(newAreas){
      let result = sqrt(newAreas)
      width = result
      height = result
      }
}
}
var obj = Area(width: 10.0, height: 20.0)
print("old area->",obj.totalAreas)
obj.totalAreas = 550.0
print("new area->",obj.totalAreas)
print("new width->",obj.width)
print("new height->",obj.height)

Output:
old area-> 200.0
new area-> 550.0
new width-> 23.4520787991171
new height-> 23.4520787991171

Explanation: 

In this example "totalAreas" is declared as computed property.In this computed property we have getter and setter to retrieve and set the property.get property calculate the total area.When use call "obj.totalAreas" its getter block  of code is executed and calculate the total area.Now when we set  obj.totalAreas = 550.0 its setter block of code is executed and calculate the width and height.

Shorthand Setter Declaration In Computed Property:If a computed property’s setter does not define a name for the new value to be set, a default name of newValue is used.

struct Area {
  var width : Double
  var height : Double
  var totalAreas : Double {
    get {
      return width * height
    }
    set{
      let result = sqrt(newValue)
      width = result
      height = result
      }
}
}
Read-Only Computed Properties:
A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value.

Example:

struct Area {
  var width : Double
  var height : Double
  var totalAreas : Double {
    get {
      return width * height
    }
 }
}
var obj = Area(width: 10.0, height: 20.0)
print("old area->",obj.totalAreas)

Output:
old area-> 200.0

Note*
You must declare computed properties—including read-only computed properties—as variable properties with the var keyword, because their value is not fixed. The let keyword is only used for constant properties, to indicate that their values cannot be changed once they are set as part of instance initialization.

Conclusion: 
Today we learn about stored and computed properties.
If you have any questions just leave a comment below and I’ll respond as soon as I can.


Monday 14 November 2016

Class vs Struct In Swift

Today we learn about class and structure used in swift.Classes and structures are general-purpose, flexible constructs that become the building blocks of your program’s code. 
You define properties and methods to add functionality to your classes and structures by using exactly the same syntax as for constants, variables, and functions.

Similarities In Class Vs Structure 
  1. Define properties to store values.
  2. Define methods to provide functionality
  3. Define subscripts to provide access to their values using subscript syntax
  4. Define initializers to set up their initial state
  5. Be extended to expand their functionality beyond a default implementation
  6. Conform to protocols to provide standard functionality of a certain kind
Difference between Class and Structure
  1. Inheritance enables one class to inherit the characteristics of another.
  2. Type casting enables you to check and interpret the type of a class instance at runtime.
  3. Deinitializers enable an instance of a class to free up any resources it has assigned.
  4. Reference counting allows more than one reference to a class instance.
  5. Classes are reference type while Structure are value type.
Note*
Structure are value type and they don't use  referencing counting.

Syntax of Class and Structure

  1. class SomeClass {
  2. // to do
  3. }
  4. struct SomeStructure {
  5. // to do
  6. }
  7. Value Type Vs Reference Type: 
      A Value Type holds the data within its own memory allocation and a Reference Type contains a pointer to another memory location that holds the real data. Reference Type variables are stored in the heap while Value Type variables are stored in the stack.
      All structures and enumerations are value types in Swift. This means that any structure and enumeration instances you create—and any value types they have as properties—are always copied when they are passed around in your code.
        Assignment and Copy Behavior for  Strings, Arrays, and Dictionaries:
        In Swift, many basic data types such as String, Array, and Dictionary are implemented as structures. This means that data such as strings, arrays, and dictionaries are copied when they are assigned to a new constant or variable, or when they are passed to a function or method.
        This behavior is different from Foundation: NSString, NSArray, and NSDictionary are implemented as classes, not structures. Strings, arrays, and dictionaries in Foundation are always assigned and passed around as a reference to an existing instance, rather than as a copy.

        Example Of Value Type And Reference Type


          class Address{
            var fullAddress:String
            var pincode: String
            init(fullAddress:String,pincode:String) {
              self.fullAddress = fullAddress
              self.pincode = pincode
            }
          }
          class Person {
            var name: String
            var address:Address
            init(name:String,address:Address) {
              self.name = name
              self.address = address
            }
          }
          var address = Address(fullAddress: "House # 98 ,Street # 3,Sector 50,Mumbai", pincode: "123456")
          let peter = Person(name: "Peter", address: address)
          let john = Person(name: "johan", address: address)
          print("Peter Address->",peter.address.fullAddress)
          print("John Address->",john.address.fullAddress)
          //Now johan moved to another location
          john.address.fullAddress = "House # 80, Sector 47 ,New Delhi"
          print("Now John Address->",john.address.fullAddress)
          print("Now Peter Address Also->",peter.address.fullAddress)

          Output:

          Peter Address-> House # 98 ,Street # 3,Sector 50,Mumbai
          John Address-> House # 98 ,Street # 3,Sector 50,Mumbai
          Now John Address-> House # 80, Sector 47 ,New Delhi
          Now Peter Address Also-> House # 80, Sector 47 ,New Delhi

          Here you can  see that Peter address is also updated due to reference type behaviour of class.

          How to solve this problem now?????? To solve this problem you have to use structure here because structure are value type.

            Convert  Address type to struct instead of class. 

                struct Address{
                  var fullAddress:String
                  var pincode: String
                  init(fullAddress:String,pincode:String) {
                    self.fullAddress = fullAddress
                    self.pincode = pincode
                  }
                }
                class Person {
                  var name: String
                  var address:Address
                  init(name:String,address:Address) {
                    self.name = name
                    self.address = address
                  }
                }
                var address = Address(fullAddress: "House # 98 ,Street # 3,Sector 50,Mumbai", pincode: "123456")
                let peter = Person(name: "Peter", address: address)
                let john = Person(name: "johan", address: address)
                print("Peter Address->",peter.address.fullAddress)
                print("John Address->",john.address.fullAddress)
                //Now johan moved to another location
                john.address.fullAddress = "House # 80, Sector 47 ,New Delhi"
                print("Now John Address->",john.address.fullAddress)
                print("Now Peter Address Also->",peter.address.fullAddress)

                Output :

                Peter Address-> House # 98 ,Street # 3,Sector 50,Mumbai
                John Address-> House # 98 ,Street # 3,Sector 50,Mumbai
                Now John Address-> House # 80, Sector 47 ,New Delhi
                Now Peter Address Also-> House # 98 ,Street # 3,Sector 50,Mumbai

                Now you see that Peter address is not updated because we make address as struct type.
                    Conclusion:
                             Today we learn about classes and structure
                              If you have any questions just leave a comment below and I’ll respond as soon as I can.