iOS 和 Swift : Ok to force unwrap tableView. 索引路径?

标签 ios swift uitableview optional-values

我有一个从 TableView Controller 到另一个 View Controller 的转接。在方法 prepare(for: sender) 中,我需要获取触发 segue 的单元格的 indexPath。在这种情况下可以强制展开索引路径吗?毕竟 prepare() 方法是通过点击表格行触发的,所以我似乎可以假设“发件人”包含对有效对象的引用是吗?

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {   
  if segue.identifier == "TheCorrectSegue" {   
    let indexPath = tableView.indexPath(for: sender as! UITableViewCell)! <-- is this OK?   
}}  

最佳答案

如果 segue 连接到 TableView 单元格,那么它是安全的,因为总是通过 sender 参数传递有效的单元格。

但实际上并不是要写更多的代码

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {   
    guard segue.identifier == "TheCorrectSegue", let cell = sender as? UITableViewCell, 
      let indexPath = tableView.indexPath(for: cell) else { return } 
      // do something with the index path
}  

关于iOS 和 Swift : Ok to force unwrap tableView. 索引路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43643417/

相关文章:

ios - 隐藏 View 并相应地重新定位其他 View

swift - 快速保存 NSManagedObjectContext 时出错

ios - 使用swift创建iOS框架

ios - CoreGraphics (drawRect) 用于在 UITableViewCell 中绘制标签和 UIImageView

ios - 使用 Swift 仅向文本添加高亮/背景

ios - 返回时出现 Swift ios 错误

ios - drawRect 不想画任何东西

ios - 如何从 iOS 中的字典中获取值

swift - 角不是 UILabel 和 UIbutton 的圆形 ios swift

ios - 自定义 UITableViewCell 不可见,我的第一个自定义单元格可见,其他不可见