I am trying to do something that with a C-style loop was easy but I am struggling with in Swift3.
I have a loop that I need to increment by different amounts depending on a value stored in an array. The code below describes it better.
let scaleIntervals: [Int] = [2,2,1,2,2,2,1]
let notes: [String] = ["A", "A#", "B", "C", "C#" "D", "D#" "E", "F" ,"G", "G#"]
var scale: [String] = []
for(var i = 0; i < notes.length; i++){
/* *Sketchy - untested* If the note in the first index of the output array
matches the current note we have completed the scale. Exit loop */
if scale[0] == notes[i]{
break
}
//Add the note to the output array and increment by the next interval
scale.append(notes[i])
i += scaleIntervals![i]
//If interval makes i larger than the notes array, loop back round
if i >= notes.length{
i -= notes.length
}
}
If you have read this far and are thinking 'that code doesn't look much like swift', that is because I am currently transitioning from JavaScript to Swift and some habits die hard.
I am after an alternative looping arrangement as for in
creates i
as a let
making it immutable throwing an error at the increment line i += scaleIntervals![i]
. I thought stride might work but I can't get my head around how to set it up.
Also using a for in where
loop with the modulo operator only works to a point because I make have large increments that could cause a false positive. That being said if I am wrong and you can make it work I would love to learn how.
I'd even accept a completely different structure (i.e. non for-loop).