1

I am new to SWIFT programming and was following Ray Wenderlich's tutorial on collection view. I found code in which they were implementing the collectionView Data source as extensions . I know what are extensions(Extensions add new functionality to an existing class) - But still I can't understand the advantages one is getting while doing such in this scenario.

extension FlickrPhotosViewController : UICollectionViewDataSource {



    //1
      override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return searches.count
      }

      //2
      override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return searches[section].searchResults.count
      }

      //3
      override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! UICollectionViewCell
        cell.backgroundColor = UIColor.blackColor()
        // Configure the cell
        return cell
      }
    }

Question - What is the difference in implementing the UICollectionViewDataSource as -

class FlickrPhotosViewController: UIViewController,UICollectionViewDataSource

And then confirming to the data source delegates. What more advantage do we have when we do it via extensions.Does it provide any other help apart from only making our program structure look good?

G.Abhisek
  • 1,034
  • 11
  • 44
  • 2
    It just gives you a nice separation in your file, so that all methods related to UICollectionViewDataSource are in one place, for example the end of your file or even in a separate file if you wanted. – totiDev Mar 04 '16 at 10:58
  • @totiG So that is the only help that we are getting from this ....? I hoped something more.....!!1 – G.Abhisek Mar 04 '16 at 11:03
  • 2
    The benefit shouldn't be underestimated. Having one coherent extension serving a single purpose greatly enhances readability and maintainability of the code. – Mike Pollard Mar 04 '16 at 11:06
  • @MikePollard So will you suggest for maintaining a neat & clean project its better to use extensions wherever possible..... as in this case. – G.Abhisek Mar 04 '16 at 11:08
  • Yes. Imagine a class implementing many protocols. Much cleaner to separate all those implementations out. Check out the Swift source code on github, they do it all the time. – Mike Pollard Mar 04 '16 at 11:15
  • 1
    I would recommend this. Whenever my code needs to conform to a Protocol, I put it into an extension at the end of the file. On the line before the extension, I typically also add in the name of the protocol I am implementing, eg: //MARK: UICollectionViewDataSource – totiDev Mar 04 '16 at 11:18

0 Answers0