gpt4 book ai didi

ios - if else 的快捷方式

转载 作者:IT王子 更新时间:2023-10-29 05:33:43 25 4
gpt4 key购买 nike

我是 swift 的新手,我在以下逻辑中闻到了错误的代码

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]
}

}

本质上,我有多个 View Controller ,我试图根据点击的 Cell 访问它们。

为什么我觉得这是糟糕的代码是因为有很多代码重复。有没有更好的方法来构建它?

最佳答案

我会定义协议(protocol):

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

让您的三个 View Controller 类符合该协议(protocol),例如:

class VC1: UIViewController, YourProtocolName {
var selection: String?

...
}

然后:

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]
}
}

关于ios - if else 的快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50625919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com