gpt4 book ai didi

swift - 结构关联枚举中的计算属性

转载 作者:行者123 更新时间:2023-11-28 06:06:37 24 4
gpt4 key购买 nike

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

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 提供一个结果。关于执行此操作的优雅方法的建议?

最佳答案

您可以使 triad 成为枚举本身的一部分:

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

关于swift - 结构关联枚举中的计算属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48030853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com