【问题标题】:Swift custom UITableViewController: switch statement case label section enumSwift 自定义 UITableViewController:switch 语句 case 标签部分枚举
【发布时间】:2015-05-13 17:14:06
【问题描述】:

为了使我的代码更具可读性和可维护性,在具有Int 类型的控制表达式的 switch 语句中使用标签而不是硬编码 Ints 的案例标签的最佳方法是什么?

例如,在我的SettingsTableViewController 中,我尝试过

enum Section : Int {
    case Phone
    case LogOut
    case DeleteAccount
}

– tableView:didSelectRowAtIndexPath:

switch indexPath.section {
case .Phone:
    // Push EditPhoneViewController
case .LogOut:
    // Log out
case .DeleteAccount:
    // Present action-sheet confirmation
}

但出现编译错误

Enum case pattern cannot match values of the non-enum type 'Int'

【问题讨论】:

    标签: ios uitableview swift enums switch-statement


    【解决方案1】:

    在开关中,您不能简单地使用indexPath.section,因为它与您的枚举类型不同。

    使用switch Section(rawValue: indexPath.section)!

    【讨论】:

    • 使用 if let section = Section(rawValue: indexPath.section) { switch section { } } 而不是使用 !如果您收到意外的部分编号,则会崩溃。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多