struct associated enum中的计算属性

问题描述 投票:1回答:1

我正在尝试在枚举和结构之间建立关系。我想在一个结构中有一个计算属性,它返回枚举的每个元素。但是,struct没有这个枚举的实例 - 它更像是一个静态实现。我正在寻找有关语法的建议,以使此代码正常工作 - 或者可能是表示我的类型的更好方法。这是示例代码:

enum ScaleDegree: Int {
    case tonic
    case supertonic
    // there's more...
}

struct Scale {
    // among other things, 
    // returns scale notes for the diatonic chords associated with the ScaleDegree
    var triad: [Int] {
        switch ScaleDegree {
        case .tonic: return [1, 3, 5]
        case .supertonic: return [2, 4, 6]
        }
    }
}

当然上面没有编译。然而,这是我正在尝试做的一个很好的例子。在这个例子中,我不想在Scale中使用ScaleDegree的实例,但我确实希望Scale能够为每个ScaleDegree提供结果。建议以优雅的方式做到这一点?

swift enums
1个回答
1
投票

你可以让triad成为enum本身的一部分:

enum ScaleDegree: Int {
    case tonic
    case supertonic

    var triad: [Int] {
        switch self {
        case .tonic:
            return [1,3,5]
        case .supertonic:
            return [2,4,6]
        }
    }
}

或者把它变成结构中的一个函数:

struct Scale {
    func triad (degree: ScaleDegree) -> [Int] {
        switch degree {
        case .tonic: return [1, 3, 5]
        case .supertonic: return [2, 4, 6]
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.