Swift switch case let语法-访问嵌套枚举上定义的函数[已关闭]

toe95027  于 12个月前  发布在  Swift
关注(0)|答案(1)|浏览(103)

已关闭此问题为not reproducible or was caused by typos。它目前不接受回答。

此问题是由打印错误或无法再重现的问题引起的。虽然类似的问题可能是on-topic在这里,这一个是解决的方式不太可能帮助未来的读者。
13天前关闭
Improve this question
我需要访问一个在嵌套枚举上定义的函数。我的设置如下:

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")

    // **** I have no idea for the syntax of the following, the code below does not work *****
    case .toolSetupStep(_) let toolStep:
        let numberNeeded = toolStep.accessMe()
    }
}

我试图获取上面的值“numberNeeded”,但我不知道访问它的语法是什么,或者是否可能。

5n0oy7gb

5n0oy7gb1#

您可以使用两种语法访问此函数及其关联值。

第一个

case .toolSetupStep(let toolStep):

这是一种常见的方法,但它有一个缺点,如果你有很多关联的值,你必须用letvar标记它们。当我们的属性既不是let也不是var时,它很有用,这样你就可以灵活地标记每个属性。

第二个:(我喜欢的一个)

我们用我们需要的类型值(letvar)作为枚举case的前缀。通过这种方式,您可以根据需要定义关联值,而无需在每个值前面加上其值类型。

case let .toolSetupStep(toolStep):
    //your code using tollStep

假设我们在toolSetupStep中有3个相关的值,我们可以很容易地像这样使用它们:

case let .toolSetupStep(toolStep,toolStep2,toolStep3):

相关问题