Showing posts with label protocol. Show all posts
Showing posts with label protocol. Show all posts

Thursday, October 3, 2019

Custom cell class datasource in MVVM design pattern



We generally pass a model to cell to configure/render and the reason behind it is, instead of passing multiple parameters, we can have a model to be passed as parameter.


Let’s take a below cell for example which is having 4 labels and in MVVM design pattern, viewmodels build and gives model to cell in cellForRowAt in viewcontroller.





This seems/sounds familiar as this is what we have been doing.
But, there are flaws in this approach.

  1. What If I want to reuse the cell?
  2. In MVVM design pattern view(in this case cell) should not hold a model(Agree?)



I can not reuse the cell efficiently as this cell is tightly coupled with a model.

First in place, this poor cell is having 4 labels and technically needs 4 stings to display. As simple as that. Isn’t it?

Then why to pass a model and create a tight coupling.

Instead of passing a model, Cell can have a datasource implemented like below.




Now cell configuration happens based on the ProductCellDataSource protocol. That means any model that confirms to this protocol can be passed to cell configure method to render the cell.




In other words, cell is just asking to send me the data as per my protocol and it is saying I am not literally worried about the model you are sending as long as it confirms to my datasource protocol.




With this approach, cell will not have any tight coupling with models(MVVM basic rule) and it can be reused by passing any model which confirms to it’s datasource protocol.

Hope this post is useful. Feel free to comment incase of any queries.


Thursday, August 9, 2018

Swift Comparable Protocol



Before reading this post, I would suggest to go through my post on Equatable protocol

Because, Comparable protocol extends from Equatable Protocol.

Equatable helps in comparing custom class objects and finding them in a collection.

Comparable protocol helps in comparing(< , > , <=, >=) and sorting of custom class objects.

<= and >= uses Equatble stuff as Comparable protocol extends from to Equatable protocol.

Most of the native classes confirm to comparable protocol which gives direct comparison access.


       
 let fruit1 = "banana"
 let fruit2 = "grapes"
        
      if fruit1 < fruit2  {
         print("YES!")
      } 
      else {
         print("NO!")
      }




Most of the native classes confirm to comparable protocol which gives direct sort() method for collection.

       
 var fruits = ["banana", "apple", "grapes"]

 fruits.sort()

 print(fruits)  //["apple", "banana", "grapes"]



Here we don’t need to write any logic.


Where as for custom classes, We need to explicitly write the sort logic by using sort(by:) method.

       
  struct Address: Equatable {
    
    let city: String
    let state: String
    let country: String
    
   }

  var addresses = [

  Address(city: "Amsterdam", state: "New York", country: "America"),

  Address(city: "Belmont", state: "California", country: "America"),

  Address(city: "Hartford", state: "Connecticut", country: "America")]
        
 addresses.sort(by: { $0.state < $1.state })





Instead of this, Address struct can confirm to Comparable protocol and we can have ability to directly compare(< , > , <=, >=).

For Equatable, we don’t need to write boiler plate code from Swift 4.1 onwards, whereas for Comparable, we need to write.

       
 struct Address: Comparable {
    
      let city: String
      let state: String
      let country: String
    
      static func < (lhs: Address, rhs: Address) -> Bool {
          return lhs.city < rhs.city
      }
    
  }



I am comparing city name for sorting here.

Now, we can directly compare our Address custom objects with comparison operators(< , > , <=, >=).

       
    let currentAddress = Address(city: "Amsterdam", state: 
            "New York", country: "America")


    let selectedAddress = Address(city: "Hartford", state: 
            "Connecticut", country: "America")
        
        if currentAddress < selectedAddress {
            print("Show current address first")
        } 
        else {
            print("Show selectedAddress address first")
        }



As we are mentioned the logic for Comparison, Our Address collection will have direct sort() method now.









       

  var addresses = [

  Address(city: "Amsterdam", state: "New York", country:      
                                                                       "America"),


  Address(city: "Belmont", state: "California", country: 
                                                                       "America"),
  
  Address(city: "Hartford", state: "Connecticut", country:     
                                                                       "America")]
        
  addresses.sort()




That’s how we can make use of Comparable protocol and have comparison quite easy like native objects.


Hope this post is useful. Feel free to comment in case of any queries.


Wednesday, August 8, 2018

Swift Equatable Protocol


In this tutorial, let’s see what is like confirming to Equatable protocol and where exactly it fits in app development.


It’s quite often we compare things/objects.

       
        let currentAddress = "New York, America"
        let selectedAddress = "New York, America"
        
        if currentAddress == selectedAddress {
            print("Deliver to current address.")
        } else {
            print("Deliver to selected address.")
        }




As these are strings, directly we can use equal to(==) operator.

What If thy are custom objects ?

       
  let currentAddress = Address(city: "Amsterdam", 
                                              state: "New York", 
                                              country: "America")

  let selectedAddress = Address(city: "Amsterdam", 
                                                state: "New York", 
                                                country: "America")
        
  if currentAddress == selectedAddress { 
            
  }




If you compare two custom objects, We get below build error,

// Binary operator '==' cannot be applied to two 'Address' operands

Here what we can do is to write a method in Address struct.

       
 struct Address {
    
    let city: String
    let state: String
    let country: String
    
    func isEqual(to address: Address) -> Bool {
        if city == address.city && 
           state == address.state && 
           country == address.country {

            return true
        }
        return false
    }
    
 }

  let currentAddress = Address(city: "Amsterdam", 
                                              state: "New York", 
                                              country: "America")

  let selectedAddress = Address(city: "Amsterdam", 
                                                state: "New York", 
                                                country: "America")
        
   if selectedAddress.isEqual(to: currentAddress) {
            
   }




This solves the scenario for now.

What if we have an array of addresses and we need to find a address in that?

And we can not directly use contains by passing element like below.

       
  var countries = ["Canada", "Australia", "India", "America"]


   let country = "India"
        
   if countries.contains(country) {
            
   }



We have to use the Array’s contains(where) closure.




       
  let addresses = [
                             Address(city: "Amsterdam", state: "New York", country: "America"), 
                             Address(city: "Belmont", state: "California", country: "America"),  

                             Address(city: "Hartford", state: "Connecticut", country: "America")
                          ]
        
  let selectedAddress = Address(city: "Hartford", state: "Connecticut", country: "America")
        
        let contains = addresses.contains { (address) -> Bool in

            return (selectedAddress.city == address.city &&
                selectedAddress.state == address.state &&
                selectedAddress.country == address.country)
        }



We need to check with the Array contains method with the same condition we used in Address struct method isEqual()


       
     func isEqual(to address: Address) -> Bool {
        if city == address.city && 
           state == address.state && 
           country == address.country {

            return true
        }
        return false
    }

    let contains = addresses.contains { (address) -> Bool in

            return (selectedAddress.city == address.city &&
                selectedAddress.state == address.state &&
                selectedAddress.country == address.country)
     }




Isn’t it a tedious job?


So, This is the use case of Equatable protocol, where it gives the easy solution/way for comparing two objects and finding an object in a collection.

It is as simple as shown below.

Let our Address structure confirm to Equatable protocol.

Earlier, prior to Swift 4.1 version, we need to implement below == static method where we can write equality logic.

       
 struct Address: Equatable {
    
    let city: String
    let state: String
    let country: String
    
    public static func == (lhs: Address, rhs: Address) -> Bool {
        return lhs.city == rhs.city &&
        lhs.state == rhs.state &&
        lhs.country == rhs.country
    }
    
 }




From Swift 4.1 onwards, we don’t need to write the boilerplate code for Equatable protocol unless we need to change the logic.

       
 struct Address: Equatable {
    
    let city: String
    let state: String
    let country: String    
    
 }



By default, boilerplate code compares all the stored properties.

       
 public static func == (lhs: Address, rhs: Address) -> Bool {


        return lhs.city == rhs.city &&
                  lhs.state == rhs.state &&
                  lhs.country == rhs.country
  }



If you want to customise you can implement the == method. In this case, If you want to compare just city and state.

       
 struct Address: Equatable {
    
    let city: String
    let state: String
    let country: String
    
    public static func == (lhs: Address, rhs: Address) -> Bool {

        return lhs.state == rhs.state &&
                  lhs.country == rhs.country
    }
    
 }



Now, we can compare objects like native things.


       
    let currentAddress = Address(city: "Amsterdam", 
                state: "New York", country: "America")


    let selectedAddress = Address(city: "Amsterdam", 
                state: "New York", country: "America")

    if currentAddress == selectedAddress {
            
    }




And also below. When we call !=, It takes the reverse of == method. No need to write extra code for !=
        
       
   if currentAddress != selectedAddress {
            
    }




So, comparing objects became easy with Equatable protocol. Let’s see finding an element in a collection if all the objects in the collection confirm to Equatable protocol.

       
 let addresses = [

          Address(city: "Amsterdam", state: "New York", country: "America"), 


          Address(city: "Belmont", state: "California", country: "America"), 


          Address(city: "Hartford", state: "Connecticut", country: "America")


  ]


  let selectedAddress = Address(city: "Hartford", state: "Connecticut", country: "America")




I want to check whether addresses collection contains selected address or not. As Address confirm to Equatable protocol and addresses array is a collection of Address objects. We get another useful and simple contains() method now.





             
 let addresses = [

          Address(city: "Amsterdam", state: 

                 "New York", country: "America"), 

          Address(city: "Belmont", state: 

                 "California", country: "America"), 

          Address(city: "Hartford", state: 

               "Connecticut", country: "America")

  ]


  let selectedAddress = Address(city: 

                            "Hartford", state: 
               "Connecticut", country: "America")


  if addresses.contains(selectedAddress) {
            
  }




We can simply find objects now using contains.

That’s how Equatable makes it easy of comparing custom objects and finding custom objects in a collection.

Hope this post is useful. Feel free to comment in case of any queries.