我有一个带有计算属性的枚举,它返回一个指示数组:
enum ScaleDegree {
case tonic
case supertonic
case mediant
case subdominant
case dominant
case submedian
case leading
var indexes: [Int] {
switch self {
case .tonic: return [0,2,4]
case .supertonic: return [1,3,5]
case .mediant: return [2,4,6]
case .subdominant: return [3,5,0]
case .dominant: return [4,6,1]
case .submedian: return [5,0,2]
case .leading: return [6,1,3]
}
}
}
我用它来从一个更大的数组中提取一个子目标:
let cMajor = ["C", "D", "E", "F", "G", "A", "B"]
let cMajorTonic = [cMajor[ScaleDegree.tonic.indexes[0]], cMajor[ScaleDegree.tonic.indexes[1]], cMajor[ScaleDegree.tonic.indexes[2]]]
cMajorTonic语法看起来很麻烦,我希望Swift 4能让我更简单地将单个元素提取到一个新数组中,但我的搜索并没有找到一个聪明的方法来做到这一点。
有没有更好的方法来写这个?
答案 0 :(得分:3)
这是一个使用map
的好地方:
let cMajor = ["C", "D", "E", "F", "G", "A", "B"]
let cMajorTonic = ScaleDegree.tonic.indexes.map { cMajor[$0] }
print(cMajorTonic)
["C", "E", "G"]
您可以将此功能添加到枚举:
func appliedTo(scale: [String]) -> [String] {
return self.indexes.map { scale[$0] }
}
然后它会变成:
let cMajorTonic = ScaleDegree.tonic.appliedTo(scale: cMajor)