You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中switch case let语法:访问嵌套枚举定义的函数

访问Swift嵌套枚举关联值并调用其方法的正确语法

你的代码问题出在switch分支中关联值的绑定语法错误,以下是修正后的完整代码:

var currentlyShowingStepIndex:Int?
var allSetupSteps:[SetupStep] = []

enum SetupStep {
    case districtSetupStep(DistrictSetupStep), toolSetupStep(ToolSetupStep)

    enum DistrictSetupStep {
        case one, two, three
    }

    enum ToolSetupStep {
        case one, two, three

        func accessMe() -> Int {
            switch self {
                case .one:
                    return 1
                case .two:
                    return 2
                case .three:
                    return 3
            }
        }
    }
}

if let index = currentlyShowingStepIndex {
    let currentStep = allSetupSteps[index]
    switch currentStep {
    case .districtSetupStep(_):
        print("asdf")
    // 正确的关联值绑定写法
    case .toolSetupStep(let toolStep):
        let numberNeeded = toolStep.accessMe()
        // 可添加打印验证结果
        print(numberNeeded)
    }
}

关键修正点:

  • 原代码中case .toolSetupStep(_) let toolStep:的语法错误,正确写法是将绑定变量直接放在关联值的位置:case .toolSetupStep(let toolStep):
  • 不需要先用_占位,直接通过let声明变量就能捕获嵌套枚举的实例,之后就可以正常调用它的accessMe()方法。

这种嵌套枚举的关联值访问是完全可行的,只要遵循Swift的枚举匹配语法,就能顺利获取内部枚举实例并调用其方法。

内容的提问来源于stack exchange,提问作者Alex Ritter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 16:33:26