我正在尝试通过Swift中的枚举器函数来计算音符的半音变化了多少,但我不知道如何应用。这是我所做的:
enum TonalityChange: String{
case C = "1/2"
case Csharp = "1"
case D = "1(1/2)"
case Dsharp = "2"
case E = "2(1/2)"
case F = "3"
case Fsharp = "3(1/2)"
case G = "4"
case Gsharp = "4(1/2)"
case A = "5"
case Asharp = "5(1/2)"
case B = "6"
}
然后我为枚举声明一个变量:
var OldTonality : B
var NewTonality : C
var Difference : //This will do the subtraction result
然后我必须将两个值相减以获得一个自然数,该自然数将让我知道如下变化:
6 - (1/2) = 5(1/2)
最后,我想发出一条警告消息,显示如下:
"Great! Tonality changed by \(Difference) tones!"
or "Great! Tonality changed by (1/2) tones!"
但是我整天都在思考如何执行此逻辑。
答案 0 :(得分:1)
使音调更改浮点数而不是字符串:
enum TonalityChange: Float {
case C = 0.5
case Csharp = 1
case D = 1.5
case Dsharp = 2
case E = 2.5
case F = 3
case Fsharp = 3.5
case G = 4
case Gsharp = 4.5
case A = 5
case Asharp = 5.5
case B = 6
}
现在您可以进行比较。
let diff = TonalityChange.B.rawValue - TonalityChange.C.rawValue
答案 1 :(得分:0)
尝试这个
enum TonalityChange: Float {
case C = 0.5
case Csharp = 1.0
case D = 1.5
case Dsharp = 2.0
case E = 2.5
case F = 3.0
case Fsharp = 3.5
case G = 4.0
case Gsharp = 4.5
case A = 5.0
case Asharp = 5.5
case B = 6.0
var formatedString : String {
switch self {
case .C : return "1/2"
case .Csharp : return "1"
case .D : return "1(1/2)"
case .Dsharp : return "2"
case .E : return "2(1/2)"
case .F : return "3"
case .Fsharp : return "3(1/2)"
case .G : return "4"
case .Gsharp : return "4(1/2)"
case .A : return "5"
case .Asharp : return "5(1/2)"
case .B : return "6"
}
}
}
let difference = TonalityChange.B.rawValue - TonalityChange.C.rawValue
let newValue = TonalityChange(rawValue :difference)
print(newValue!.formatedString)