Last active
September 5, 2017 15:35
-
-
Save sketchytech/b14b8c906481a17a8d29 to your computer and use it in GitHub Desktop.
Circle of Fifths in Swift: Notes for Key
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
// randomly thinking about how you might use circle of fifths to return notes in any given musical Key | |
enum KeySignature:String { | |
case A, B, C, CSharp = "C♯",D, E, F, G, AFlat = "A♭", BFlat = "B♭", CFlat = "C♭", DFlat = "D♭", EFlat = "E♭", GFlat = "G♭" | |
case Am, Bm, Cm, Dm, Em, Fm, Gm, FSharpm = "F♯m", CSharpm = "C♯m", GSharpm = "G♯m", EFlatm = "E♭m", BFlatm = "B♭m", AFlatm = "A♭m", ASharpm = "A♯m" | |
func major() -> KeySignature { | |
switch self { | |
case .Am: | |
return KeySignature.C | |
case .Em: | |
return KeySignature.G | |
case .Bm: | |
let b = KeySignature.D | |
return b | |
case .FSharpm: | |
return KeySignature.A | |
case .CSharpm: | |
return KeySignature.E | |
case .GSharpm: | |
return KeySignature.B | |
case .EFlatm: | |
return KeySignature.GFlat | |
case .BFlatm: | |
return KeySignature.DFlat | |
case .Fm: | |
return KeySignature.AFlat | |
case .Cm: | |
return KeySignature.EFlat | |
case .Gm: | |
return KeySignature.BFlat | |
case .Dm: | |
return KeySignature.F | |
case .AFlatm: | |
return KeySignature.CFlat | |
case .ASharpm: | |
return KeySignature.CSharp | |
default: | |
return self | |
} | |
} | |
func notesForKey() -> [String] { | |
var k = ["C","D","E","F","G","A","B"] | |
let key = self.major() | |
if key.rawValue == "F" || key.rawValue.characters.last == "♭" { | |
repeat { | |
k = [String](k.suffix(4) + k.prefix(3)) | |
k[3] = k[3] + "♭" | |
} | |
while key.rawValue != k[0] | |
} | |
else { | |
while key.rawValue != k[0] { | |
k = [String](k.suffix(3) + k.prefix(4)) | |
k[6] = k[6] + "♯" | |
} | |
} | |
// Fixes ordering for relative minors | |
var ind = 0 | |
for i in k.enumerated() { | |
if i.element.first == self.rawValue.first { | |
ind = i.offset | |
} | |
} | |
let arraySlice = k[k.index(k.startIndex, offsetBy: ind)..<k.endIndex] + k[k.startIndex..<k.index(k.startIndex, offsetBy: ind)] | |
return Array(arraySlice) | |
} | |
} | |
KeySignature.E.notesForKey() // ["E", "F♯", "G♯", "A", "B", "C♯", "D♯"] | |
KeySignature.BFlatm.notesForKey() // ["B♭", "C", "D♭", "E♭", "F", "G♭", "A♭"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment