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?
The if/else if statement allows you to create a chain of if statements. The if statements are evaluated in order until one of the if expressions is true or the end of the if/else if chain is reached. If the end of the if/else if chain is reached without a true expression, no code blocks are executed.
A multi-way selection is written when there are a series of conditions with different statements for each condition. Multi-way selection is performed using if-else-if statements such that exactly one section of code is executed based on the first condition that evaluates to true.
You use conditionals to make decisions in your Swift code, with if, else if and else. If this happens, then do that. This is called control flow, because you use it to control the way your code flows. In this tutorial you'll learn how to use the if-statement in your Swift code.
I'd define protocol:
protocol YourProtocolName: 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, YourProtocolName {
var selection: String?
...
}
And then:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dest = segue.destination as? YourProtocolName,
let index = collectionView?.indexPathsForSelectedItems?.first {
dest.selection = cellLabels[index.row]
}
}
guard let index = collectionView?.indexPathsForSelectedItems?.first else { return }
switch segue.destination {
case let dest1 as VC1: dest1.selection = cellLabels[index.row]
case let dest2 as VC2: dest2.selection = cellLabels[index.row]
case let dest3 as VC3: dest3.selection = cellLabels[index.row]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With