【问题标题】:Duplicated code in switch cases that needs executing需要执行的切换案例中的重复代码
【发布时间】:2019-12-11 17:01:14
【问题描述】:

我有以下处理 UI 状态的enum

enum UIState {
    case loading
    case populated
    case empty
    case error(Error)
}

在视图控制器中,我使用switch 来检查每个状态并相应地更新 UI。

private func updateUI() {
    switch state {
    case .loading:
        showProgressView()
    case .populated, .empty:
        hideProgressView()
    case .error(let error):
        hideProgressView()
        showErrorAlert(error)
    }
}

hideProgressView() 方法需要在除loading 之外的所有情况下调用。在error 的情况下,除了调用hideProgressView() 方法之外,我还显示了一个警告

如您所见,我在两种情况下调用hideProgressView() 方法时存在少量重复代码。有没有办法在一种情况下合并重复的方法调用?我尝试了以下方式,

switch state {
case .loading:
    showProgressView()
case .error(let error):
    showErrorAlert(error)
case .populated, .empty, .error:
    hideProgressView()
}

但我在最后一种情况下收到以下警告。

大小写已由先前的模式处理;考虑删除它

案件永远不会被执行

【问题讨论】:

    标签: ios swift enums switch-statement


    【解决方案1】:

    也许最简单的方法是这样的:

    switch state {
        case .loading:
            showProgressView()
        case .error(let error):
            showErrorAlert(error)
            fallthrough
        case .populated, .empty:
            hideProgressView()
        }
    

    您可以通过以下方式获取更多信息:https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html#ID140

    【讨论】:

    • 谢谢!我也查看了fallthrough,但在最后一步中再次添加error 是错误的,导致错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多