Building a MIDI Sequencer App: Part 2

I recently read a very good Swift dev article entitled “Avoiding primitive obsession in Swift.” The general idea is to avoid using primitive types — things like Ints or Strings — when you can be more specific with the type of information you are passing around to functions and such. This can help your code be more readable, and make everything a bit more type safe. Nice.

So with this in mind, I’m going to rewrite some of the code I’ve been using in my MIDI Sequencer app. I have a class: OscSequencer (I need to rename this class). This is the main sequencer class in my program. Using the AudioKit framework, it generates a sequence of notes from a dictionary. Here’s the declaration of that function:

func generateSequence(fromDictionary: [Int: (Bool, Int)])

That’s fine, and it works, but it’s kind of an ugly way to express what I’m trying to do. In my dictionary argument, the key represents the beat number in my ‘musical score’ and the value is a tuple. The bool represents if a note should be played at this beat, and the Int represents the MIDI note number that should be played. Let’s come up with a better way to represent this.

struct Score {
}

Within my fancy new Score class, I’m going to declare some typealiases. If you’re unfamiliar with typealias, all it’s doing is declaring a word to represent a different type.

struct Score {
typealias Beat = Int
typealias Note = Int
}

Anytime forward I create an instance of Note or Beat, I’m really just declaring an Int. The difference is in the name only. So what’s the point? Well, we can now represent our previous dictionary like so:

struct Score {
typealias Beat = Int
typealias Note = Int
var sheet = [Beat: (Bool: Note)]
}

I like that! It’s a small but nice difference. You get a much better idea of what the key and values are supposed to represent. We can also change our function to read something like this:

func generateSequence(from score: Score)

Now, within this function, I can use score.sheet to generate our new musical sequence. In addition, I can attach any other information I may need along with the Score struct, such as time signatures, or tempo.

Short post today, but this is a cool concept and fits right in with everything I know about Swift. Just another way to get some safe, clear, and expressive code.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.