Eric George
Eric George

Reputation: 246

Computed property in struct associated enum

I'm trying to build a relationship between an enum and struct. I would like to have a computed property in a struct that returns for each element of an enum. However, the struct doesn't have an instance of this enum - it's more of a static implementation. I'm looking for suggestions on syntax to make this code work right - or perhaps a better way of representing my types. Here is example code:

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]
        }
    }
}

Of course the above doesn't compile. However, it's a good example of what I'm trying to do. In this example, I don't want an instance of ScaleDegree in Scale, but I do want Scale to be able to provide a result for every ScaleDegree. Suggestions on an elegant way to do this?

Upvotes: 1

Views: 1500

Answers (1)

Code Different
Code Different

Reputation: 93161

You can make triad part of the enum itself:

enum ScaleDegree: Int {
    case tonic
    case supertonic

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

Or turn it into a function in the struct:

struct Scale {
    func triad (degree: ScaleDegree) -> [Int] {
        switch degree {
        case .tonic: return [1, 3, 5]
        case .supertonic: return [2, 4, 6]
        }
    }
}

Upvotes: 1

Related Questions