swifty way of doing if else

  • A+
Category:Languages

I am a newbie in swift and I smell a bad code in the following logic

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {      if let dest = segue.destination as? VC1,         let index =  collectionView?.indexPathsForSelectedItems?.first{         dest.selection = self.cellLabels[index.row]     }     if let dest2 = segue.destination as? VC2,         let index2 =  collectionView?.indexPathsForSelectedItems?.first{         dest2.selection = self.cellLabels[index2.row]     }     if let dest3 = segue.destination as? VC3,         let index3 =  collectionView?.indexPathsForSelectedItems?.first{         dest3.selection = self.cellLabels[index3.row]     }  } 

Essentially, I have multiple view controllers which I am trying to reach to depending on which Cell is tapped to.

Why I feel this is bad code is because there is a lot of code repeation. Is there a better way to structure this?

 


I'd define protocol:

protocol HasSelection: class {     var selection: String? { get set }  // obviously, use whatever type that is appropriate in your case } 

Have your three view controller classes conform to that protocol, e.g.:

class VC1: UIViewController, HasSelection {     var selection: String?      ... } 

And then:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {     if let dest = segue.destination as? HasSelection,         let index =  collectionView?.indexPathsForSelectedItems?.first {         dest.selection = cellLabels[index.row]     } } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: