Swift多Segue跳转重复代码优化方案咨询
优化重复的Segue准备代码
嘿,作为Swift新手就能察觉到代码重复并想要优化,这真的是个很棒的习惯!你现在的代码里确实有大量重复的逻辑——每次都是获取选中的index、取出对应的文本,然后给不同的VC赋值。下面给你两种更优雅的结构化实现方式,推荐第一种,扩展性更强:
方案一:使用协议统一处理(推荐)
既然VC1、VC2、VC3都需要接收selection这个数据,我们可以定义一个协议来规范这个行为,这样就能把重复的逻辑合并成一次处理:
第一步:定义协议
首先创建一个协议,规定需要接收选中内容的ViewController必须实现的属性(根据你cellLabels的实际类型调整属性类型,比如如果是Int就改成Int?):
protocol SelectionReceiver: UIViewController { var selection: String? { get set } }
第二步:让目标VC遵守协议
修改VC1、VC2、VC3的定义,让它们遵守这个协议(如果已经有selection属性,只要声明遵守协议就行):
class VC1: SelectionReceiver { var selection: String? // 你的VC1原有代码... } class VC2: SelectionReceiver { var selection: String? // 你的VC2原有代码... } class VC3: SelectionReceiver { var selection: String? // 你的VC3原有代码... }
第三步:简化prepare方法
现在你可以把原来的多个if判断合并成一次,代码瞬间清爽很多:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // 先统一获取选中的文本,提前做非空判断 guard let selectedIndexPath = collectionView?.indexPathsForSelectedItems?.first, let selectedContent = cellLabels[selectedIndexPath.row] as? String else { return } // 只要目标VC遵守了协议,就可以直接赋值 if let destinationVC = segue.destination as? SelectionReceiver { destinationVC.selection = selectedContent } }
这种方式的好处是:以后如果新增VC4、VC5需要同样的逻辑,只要让它们遵守SelectionReceiver协议,完全不用修改prepare方法,完美符合开闭原则。
方案二:利用Segue标识符做Switch判断
如果你的每个Segue都设置了唯一的标识符(比如在Storyboard里给Segue命名为showVC1、showVC2),也可以用switch来替代多个if,虽然不如协议优雅,但也能减少重复:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let selectedIndexPath = collectionView?.indexPathsForSelectedItems?.first, let selectedContent = cellLabels[selectedIndexPath.row] else { return } switch segue.identifier { case "showVC1": (segue.destination as? VC1)?.selection = selectedContent case "showVC2": (segue.destination as? VC2)?.selection = selectedContent case "showVC3": (segue.destination as? VC3)?.selection = selectedContent default: // 处理未匹配的Segue break } }
两种方案里,协议的方式更适合长期维护,尤其是当你有多个类似的ViewController需要处理相同逻辑时,能大大降低代码冗余。
内容的提问来源于stack exchange,提问作者frazman
相关产品推荐
相关产品推荐

