我有一个UITableViewController设置为一个UIViewController。
我做了一个全局counter
,以跟踪在UITableView中选择了哪一行。因为根据选择的行,所显示的UIViewController中的某些信息将更改。
我认为可以整理一下,以便dayx
序列仅需调用一次,并且counter
可以根据选择的行进行相应的更改?但是我很难弄清楚。
这是我目前拥有的东西,它可以正常工作,但看起来很乱吗?:
//what happens when row is selected
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
counter = 0
self.performSegue(withIdentifier: "dayx", sender: self)
} else if indexPath.row == 1 {
counter = 1
self.performSegue(withIdentifier: "dayx", sender: self)
}
else if indexPath.row == 2 {
counter = 2
self.performSegue(withIdentifier: "dayx", sender: self)
}
else if indexPath.row == 3 {
counter = 3
self.performSegue(withIdentifier: "dayx", sender: self)
}
else if indexPath.row == 4 {
counter = 4
self.performSegue(withIdentifier: "dayx", sender: self)
}
else if indexPath.row == 5 {
counter = 5
self.performSegue(withIdentifier: "dayx", sender: self)
}
else if indexPath.row == 6 {
counter = 6
self.performSegue(withIdentifier: "dayx", sender: self)
}
}
答案 0 :(得分:1)
使用flatMap
:
Swift 4.0
indexPath.flatMap {
print($0)
counter = $0
self.performSegue(withIdentifier: "dayx", sender: self)
}
稍后:
let _ = indexPath.compactMap {
counter = $0
self.performSegue(withIdentifier: "dayx", sender: self)
}
了解flatMap
的基础。阅读这篇文章Replacing flatMap With compactMap
如果您所有的行都打算做performSegue
。简单:
//what happens when row is selected
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
counter = indexPath.row
self.performSegue(withIdentifier: "dayx", sender: self)
}