简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM