使用 Swift 的面向协议编程定义 Segue 标识
回溯到八月份,我观看了 Swift in Practice WWDC15 这个超赞的视频。视频的第一部分让我印象十分深刻,因此我针对这部分写了一篇博客—— A Beautiful Solution to Non-Optional UIImage Named in Swift ——然后我最终开始准备写关于这个视频的第二部分,甚至其它更多令人激动的部分(毕竟,假期是最好的写博客的时机)(译者注:大神就是这样啊,假期不是用来玩的,反而是写博客的大好时机)。 这次,我准备写的是:处理多个 segue 标识的优雅解决方案。你猜对了!就是使用协议。 今天就让我们开始针对你的选择展开旅程吧。你会选择:红色药丸还是蓝色药丸...(译者注:如果你看不懂这个梗的话,我建议你去补习一下黑客帝国)
问题的出现很不幸地,Segue 标识一般都是基于字符串的硬编码。当它们与 Storyboard 一起使用时,你必须在代码当中到处复制这些字符串 – 这确实很容易产生错误拼写的情况。 // ViewController.swift @IBAction func onRedPillButtonTap(sender: AnyObject) { // 我在这里硬编码了红色药丸的segue标识 performSegueWithIdentifier("TheRedPillExperience",sender: self) } @IBAction func onBluePillButtonTap(sender: AnyObject) { // 我在这里硬编码了蓝色药丸的segue标识 performSegueWithIdentifier("TheBluePillExperience",sender: self) } 当然,将来如果你决定要改变一个 segue 的标识,你就必须在硬编码这些字符串的全部地方去修改它们的名称。这当然就有可能导致更多潜在的错误,比如错误的复制/粘贴以及错误的拼写。 为了减少错误情况的发生,当一个 ViewController 中使用到了多个 segue 的标识时,我都使用枚举来处理。 // ViewController.swift enum SegueIdentifier: String { case TheRedPillExperience case TheBluePillExperience } 但是这又带来了别的问题。最主要的就是代码的丑陋和臃肿: // ViewController.swift @IBAction func onRedPillButtonTap(sender: AnyObject) { // 这行代码有点长了 performSegueWithIdentifier(SegueIdentifier.TheRedPillExperience.rawValue,sender: self) } @IBAction func onBluePillButtonTap(sender: AnyObject) { // 这个也很长 performSegueWithIdentifier(SegueIdentifier.TheBluePillExperience.rawValue,sender: self) } 当我们处理 // ViewController.swift override func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject?) { // 解包所有东西!!! if let identifier = segue.identifier { if let segueIdentifier = SegueIdentifier(rawValue: identifier) { switch segueIdentifier { case .TheRedPillExperience: print(" |