Annotated Swift links

Swift has only been out for a few weeks; but there’s a lot being written as people are playing around with the language. Here’s an annotated list of links about the language and how to get things done in it.

Introductions and basics

Style

  • Style guide - Ray Wenderlich has published his Swift style guide. I mostly agree with how he does things; but I find 2-space indentation difficult to read. It’s 4 for me.

Design Patterns in Swift

Applications of common technologies with Swift

Under the hood

NSURLSession & NSURLConnection with Swift

NSURLSession

An example of using NSURLSession in Swift. Note, to do this in an Xcode Playground, you’ll need to import XCPlayground and call XCPSetExecutionShouldContinueIndefinitely()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import Cocoa
import XCPlayground

// allow the asynchronous task to continue, set timeout in console
XCPSetExecutionShouldContinueIndefinitely()

let url = NSURL(string:"http://97.88.225.91:5309/scheck")
var session = NSURLSession.sharedSession()

// use a separate handler function in lieu of doing it inline for clarity
func apiHandler(data:NSData!, response:NSURLResponse!, error:NSError!) {
if error {
println("API error: \(error), \(error.userInfo)")
}
var jsonError:NSError?
var json:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as NSDictionary
if jsonError {
println("Error parsing json: \(jsonError)")
}
else {
let status:String? = json["msg"] as? String
println("server status: \(status)")
}
}
var task:NSURLSessionDataTask = session.dataTaskWithURL(url, completionHandler:apiHandler)
task.resume()

NSURLConnection

If we wanted to do the same thing with NSURLConnection:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import Cocoa
import XCPlayground

// allow the asynchronous task to continue, set timeout in console
XCPSetExecutionShouldContinueIndefinitely()

let url = NSURL(string:"http://97.88.225.91:5309/scheck")
let urlReq = NSURLRequest(URL: url)
let queue = NSOperationQueue()

NSURLConnection.sendAsynchronousRequest(urlReq, queue: queue, completionHandler: { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if error {
println("API error: \(error), \(error.userInfo)")
}
var jsonError:NSError?
var json:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as NSDictionary
if jsonError {
println("Error parsing json: \(jsonError)")
}
else {
let status:String? = json["msg"] as? String
println("server status: \(status)")
}
})

References

Hobby Lobby is not a person

In a regrettable 5:4 decision[1], the Supreme Court of the United States ruled in Burwell v. Hobby Lobby that closely held for-profit companies can be exempt from a law to which they object on religious grounds. The majority opinion delivered by Samuel Alito maintains, in essence, that the Department of Health and Human Services contraception mandate substantially burdens the free exercise of religion. Alito also wrote that the government’s penalty on Hobby Lobby would have the result that “companies would face a competitive disadvantage in retaining and attracting skilled workers.” Skilled workers? Apparently Justice Alito has never shopped at Hobby Lobby.

Justice Ginsburg wrote the dissent with Justices Sotomayor, Breyer, and Kagan concurring.

“In a decision of startling breadth, the Court holds that commercial enterprises, including corporations, along with partnerships and sole proprietorships, can opt out of any law (saving only tax laws) they judge incompatible with their sincerely held religious beliefs.”

“In the Court’s view, RFRA (Religious Freedom Restoration Act) demands accommodation of a for-profit corporation’s religious beliefs no matter the impact that accommodation may have on third parties who do not share the corporation owners’ religious faith — in these cases, thousands of women employed by Hobby Lobby and Conestoga or dependents of persons those corporations employ. Persuaded that Congress enacted RFRA to serve a far less radical purpose, and mindful of the havoc the Court’s judgment can introduce, I dissent.”

The Court is wrong.

Corporations are not people. Perhaps Texas, the Execution Capital of the US[2], would like to put one to death. Hobby Lobby is not a person. The Bill of Rights is addressed to people not corporations. Corporations don’t have religious beliefs. They make stuff, do stuff, and sell stuff. They employee people - people against whom they are not permitted to discriminate. (Or so we thought.)

Even more problematic is that the decision grants “closely-held for-profit companies” rights that ordinary individual citizens do not have. I cannot claim exemption from any law on the grounds of religious belief. But the owners of Hobby Lobby and its ilk can cry that their imaginary rights to Free Exercise are infringed; and they are granted an exemption.

To make matters substantially worse, the Supreme Court issued a temporary injunction barring the Federal government from requiring Wheaton College to fill out a form certifying that it has a sincerely held religious objection to contraception services. Such emergency injunctions are rarely granted by the Supreme Court and then only when rights are clearly infringed. In this case, it was Justice Sotomayor who wrote a scathing dissent[3]:

“Those who are bound by our decisions usually believe they can take us at our word. Not so today. After expressly relying on the availability of the religious-nonprofit accommodation to hold that the contraceptive coverage requirement violates RFRA as applied to closely held for-profit corporations, the Court now, as the dissent in Hobby Lobby feared it might, see ante, at 29–30 (GINSBURG, J., dissenting), retreats from that position. That action evinces disregard for even the newest of this Court’s precedents and undermines confidence in this institution…The Court grants Wheaton a form of relief as rare as it is extreme: an interlocutory injunction under the All Writs Act, 28 U. S. C. §1651, blocking the operation of a duly enacted law and regulations, in a case in which the courts below have not yet adjudicated the merits of the applicant’s claims and in which those courts have declined requests for similar injunctive relief.”

“The sincerity of Wheaton’s deeply held religious beliefs is beyond refute. But as a legal matter, Wheaton’s appli- cation comes nowhere near the high bar necessary to warrant an emergency injunction from this Court. For that reason, I respectfully dissent.”

“Let me be absolutely clear: I do not doubt that Wheaton genuinely believes that signing the self-certification form is contrary to its religious beliefs. But thinking one’s religious beliefs are substantially burdened – no matter how sincere or genuine that belief may be – does not make it so”

Indeed. This is precisely why the wall of separation must be high and impermeable. How can the courts test the sincerety and validity of a belief that a person or institution claims to hold as a religious belief? Since the task is impossible, it is best to afford no such exemptions. Perhaps it is best, then that each of us lives in accordance with our own values and preferences recognizing that those values and preferences are not necessarily shared by all and that we can use neither law, nor force, nor any other form of coercion to impose them on others.

These two decision undermine the wall of separation; and the authority and prudence of the Court is underminded when such capricious applications of emergency injunctive relief of a duly enacted law are granted.

What an upside-down world we live in when commercial enterprises enjoy rights that private citizens do not.


  1. Burwell, Secretary of Health and Human Services, et al. v. Hobby Lobby Stores, Inc., et al., No. 13-354 Link

  2. In fairness, Texas is not the execution capital of the US when per capita figures are considered. Oklahoma kills more of its citizens per capita than any other state. But in absolute terms, don’t mess with Texas.

  3. Wheaton College v. Sylvia Burwell, Secretary of Health and Human Services, et al. Link

We are not materialist enough

While reading Juliet Schor’s book “Plenitude”, I was struck by a quote that she presents in part in the book. The quote is from Raymond Williams’ “Advertising: The Magic System”:

“It is often said that our society is too materialist, and that advertising reflects this. We are in the phase of a relatively rapid distribution of what are called ‘consumer goods’, and advertising, with its emphasis on ‘bringing the good things of life’, is taken as central for this reason. But it seems to me that in this respect our society is quite evidently not materialist enough, and that this, paradoxically is the result of a failure in social meaning, values and ideals.” [1]

Of course, when most of us refer to materialism, we are thinking about an orientation toward consumer goods, often with a obsessional focus on their symbolic values. But Williams raises a critical point, one that is key to our inaction on climate change. Although we are clearly fixated on consumer goods, we are so completely disconnected from their production that have nearly lost sight of their materiality.

The idea that we are disconnected from the means of production is in no way a new idea, of course. In the 1970’s Wendell Berry wrote that “specialization” in our societal roles was responsible for many of the problems, environmental and otherwise, that arose in the industrial era and beyond. As Michael Pollan wrote about Berry’s work:

“Our society assigns us a tiny number of roles: we’re producers (of one thing) at work, consumers of a great many other things the rest of the time, and then once a year or so we vote as citizens. Virtually all of our needs and desires we delegate to specialists of one kind or another — our meals to agribusiness, health to the doctor, education to the teacher, entertainment to the media, care for the environment to the environmentalist, political action to the politician.”[2]

When we consider the activities of humans in totality, each of us as individuals is responsible for only a tiny fraction of the knowledge and skill required to complete those activities. For example, few of us know how to fly a modern commercial jet airliner. But even those who do, have only a rudimentary idea of how the engines are put together, how the fan blades are cast, how the metal from which they are cast was mined, and so forth. The more complicated our built world becomes, the more disconnected we become from all of the details that comprise the “big picture.”

Specialization is what allows to have jet airliners and all of the other wonders of modern civilization. But Pollan and Berry point out that the unintended consequences loom large. Pollan writes:

“Specialization is what allows me to sit at a computer thinking about climate change. Yet this same division of labor obscures the lines of connection — and responsibility — linking our everyday acts to their real-world consequences, making it easy for me to overlook the coal-fired power plant that is lighting my screen, or the mountaintop in Kentucky that had to be destroyed to provide the coal to that plant, or the streams running crimson with heavy metals as a result.”

Pollan goes on to write that cheap energy is what allowed us to achieve and maintain this degree of specialization. Inexpensive fossil fuel allows us to pay others to produce our food for us and ship it long distances. As a thought experiment he asks us to consider what happens when the power goes out. Immediately we begin to think of all the things that we need to do for ourselves. We also begin to think about whether our neighbors are experiencing the same problem. In short, when energy is withdrawn from the equation of our daily lives, our connection to the community zooms into clearer focus. By artificially manipulating the cost of fossil fuel, we are making it so cheap that we can afford to hide from view the enormous costs of production.

f*ck Shell

What is the solution? Ultimately, perhaps there is no systematic solution given our planet’s overpopulation with humans. How can billions ever agree? It may be that as Wendell Berry said specialization is a “disease of modern character” and the solution lies in each of us becoming just a little less specialized and a little less dependent on consuming in a way that ignores the real costs of production.


  1. Williams, Raymond. “Advertising: The Magic System”. The Advertising and Consumer Culture Reader. Eds. McAllister, Matthew P., and Joseph Turow. New York: Routledge, 2009. 13-24.

  2. Pollan, Michael. “Why bother?”. The New York Times 2008 April, 2008. Web. 15 Jun. 2014 http://www.nytimes.com/2008/04/20/magazine/20wwln-lede-t.html Link

Completion handlers in Swift

When executing a concurrent operation, we often use completion handlers to execute a code block on completion. In Swift, closures are the way to accomplish that task.

Declaring a function with a completion handler

In the function definition, we can fully declare the closure:

1
2
3
func doSomething(flag:Bool, completionHandler:(success:Bool) -> Void) {
completionHandler(success:true)
}

and call the function:

1
2
3
4
5
var f = Foo()
// flag parameter name is optional here
f.doSomething(false, completionHandler:{(success:Bool) -> Void in
println("value = \(success)")
})

Using typealias

In Objective-C we’d use a typedef for a block to simplify the method declaration that uses it. We can use typealias in Swift to do the same thing.

1
typealias FooCompletionHandler = (obj:AnyObject?, success:Bool?) -> Void

which can be used in a function definition:

1
2
3
func useAliasHandler(completionHandler:FooCompletionHandler) {
completionHandler(obj:nil, success:true)
}

and called in this fashion:

1
2
3
f.useAliasHandler({(obj:AnyObject?, success:Bool?) -> Void in
println("hi")
})

It appears that you still must supply the closure arguments in the function call. I could be wrong.

Here are all of my noodlings with closures:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import Foundation

// in ObjC we would define a block with typedef
// in swift it's typealias with a closure
typealias FooCompletionHandler = (obj:AnyObject?, success:Bool?) -> Void

class Foo {
// function with a completion handler
func doSomething(flag:Bool, completionHandler:(success:Bool) -> Void) {
completionHandler(success:true)
}

// function with a typealias'd completionHandler
func useAliasHandler(completionHandler:FooCompletionHandler) {
completionHandler(obj:nil, success:true)
}

/* try another return type in block */
func doSomethingElse(completionHandler:(data:String) -> Void) {
var chars:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
chars += chars.lowercaseString
var s = ""
for i:Int in 1...10 {
let r:UInt32 = arc4random() % UInt32(countElements(chars))
let index = advance(chars.startIndex, Int(r))
let char:Character = chars[index]
s = s + char
}
completionHandler(data:s)
}
}

var f = Foo()
// completionHandler parameter name is optional here
f.doSomething(false, completionHandler:{(success:Bool) -> Void in
println("value = \(success)")
})

// completionHandler parameter name may not be used here
f.doSomethingElse( {(data:String) -> Void in
println("data = \(data)")
})

References

  • Swift - Creating Methods with Closures, Michael Kral Link
  • Notes from Coding in Swift, Tal Bereznitskey Link
  • Swift Functions and Closures, Andrew Carter Link

A blast from the past

Hailstone numbers

I was researching Collatz sequences for a tutorial I was writing on lambda expressions in Haskell when I remembered an old article from Scientific American about “hailstone numbers” that I read back in high school. Having found that article, I went looking for some of my other old favorites from the mid 80’s.

Hailstone numbers

During high school I was fasicnated by algorithms. This is a peculiar one because it involves a conjecture that hasn’t been proven. The algorithm is this: take any initial whole number value. If the number is even, divide it by 2. If it is odd, multiply it by 3 and add 1. Continue the same process until reaching 1. The sequence thus formed begins with the initial value and ends with 1. The length of this sequence is highly variable. The conjecture itself asserts that all sequences terminate with one.

The paper presented algorithms in BASIC and some version of assembly language, probably 8086. I did a lot of work in Z80 assembler back in high school and the registers don’t look familiar to me - hence my guess about 8086. The comment about BASIC being intolerably slow is funny. (You think?)

The author also talks about the possibility of using the transformations in a backwards direction as a means of gaining insight about a general proof. The problem, of course as he acknowledges, is that the algorithm is deterministic in the forward direction but ambiguous in the backwards direction.

Turning fine art into drivel

This was a fascinating and silly article that was built around Sir Arthur Eddington’s conjecture about probabilities: “If an army of monkeys were strumming on typewriters, they might write all the books in the British Museum.” The author, Brian Hayes, goes on to talk about the statistics of language and builds an algorithmic approach to generating text based on the frequency of character frequencies of n length in a source text. He goes on to experiment with combining source texts, performing mathemical transforms on the statistics, etc.

I spent hours recreating these algorithms, playing around with them, optimizing them (well as best as you could back in the 1980’s). It was all very silly; but it reinforced for me a fascination with language and free-range experimentation.

Mandelbrot

This was another article that was fascinating in the day. The utility of fractals in computer generated graphics was barely appreciated when this article first came out. In the last sentence of the paper, there’s a prescient comment about this utility: “In a future column I hope to report on some of the amazing cinematic effects produced in the Lucasfilm laboratory.” For a while, I was so fascinated by the beauty of fractals, particularly the mysterious Mandelbrot set, that bought his textbook and played around with writing a fractal graphics generator on the Mac. This was long before OS X, Objective-C, etc. I think it must have been in Pascal.

The applications of fractals are well-known now; but at the time it was cool stuff. There are still Mac-based fractal generators and explorers out there. I just checked Fraqtive which looks pretty cool.

Do gifted & talented tracks increase racial disparities?

The NY Times today ran a collection of Room for Debate pieces[1] on the topic of gifted and talented programs in public education.

One editorial[2] in particular called for the elimination of these programs on the grounds that it creates a de facto racial segregation in public education. In the New York City public school system, 70% of children are either African-American or Latino, whereas more than 70% of kindergarten students in gifted and talented programs were of white or Asian descent.

I’m about as progressive as any; but this is wrong. It is almost certainly ineffective to attempt to improve the outcomes by eliminating programs that benefit talented, motivated students. It is regretable that we (still) live in a country where such racial inequalities still exist. But stunting of opportunity is not the right way to correct it.

Those who would eliminate G&T tracks do so with the mistaken belief that if you have four children in a classroom, with IQ’s of 80,90,110, and 120; that you’ll end up with four kids of average intelligence. It doesn’t work that way. The kids on the lower end of the range may lack the foundational experiences that will enable them to take advantage of whatever benefits are mined from the G&T programs. And the kids on the upper end are likely to be bored and under-motivated by the experience. Nine pregnant women can’t deliver a baby in one month.

The recommended solution is to provide a “gifted education for all.” That certainly seems to be the egalitarian solution; but it ignores the very real difficulties of implementation. It would invariably mean more stratification of students, the very outcome the authors of this piece seek to avoid.


  1. Room for Debate (2014-06-04). The New York Times Link

  2. Potter, H. & Tipson, D. Eliminate Gifted Tracks (2014-06-04). The New York Times Link

Whoa, Swift!

The biggest news that Apple dropped at WWDC 2014 this year is the introduction of the Swift programming language[1].

It’s going to take a while to sort out the syntax and get used to writing in an entirely new language. I’m not quite sure what to think of the change. I’ve been thinking and writing in Objective-C for so long that it’s very comfortable. I don’t despise its square brackets message-passing notation, the way some developers who are new to the platforms do.

I’ve been learning Haskell for a few weeks and writing about it; and I’ll probably do the same for Swift as time permits. It’s hard not to just dive in, though. So hard, in fact, that I rewrote a little admin tool that I previously wrote in Objective-C. I was curious about how the interaction between Cocoa and Swift would go. The tool just scans the Downloads and Desktop directories for any “qfx” files[2] and deletes them.

Here’s the ObjC version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
@autoreleasepool {

void (^processDirectory)(NSString *,NSFileManager *) = ^(NSString *directory,NSFileManager *fm){
NSDirectoryEnumerator *enumerator = [fm enumeratorAtPath:directory];
NSString *path;
while( path = [enumerator nextObject] ) {
if( [[path pathExtension] isEqualToString:@"qfx"] ) {
NSError *deleteError = nil;
if( ![fm removeItemAtPath:[directory stringByAppendingPathComponent:path] error:&deleteError] )
NSLog(@"ERROR | unable to remove item at path %@. %@",path, deleteError);
}
}
};

NSFileManager *fm = [[NSFileManager alloc] init];
[@[@"Desktop",@"Downloads"] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:obj];
processDirectory(directory,fm);
}];

}
return 0;
}

and the Swift version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import Foundation

func processDirectory(directory:String, fm:NSFileManager) {
let contents:NSArray = fm.contentsOfDirectoryAtPath(directory, error: nil)
let predicate:NSPredicate = NSPredicate(format: "pathExtension == 'qfx'")
let qfxFiles = contents.filteredArrayUsingPredicate(predicate)
for object : AnyObject in qfxFiles {
let file = object as NSString
var error: NSError?
if !fm.removeItemAtPath(directory.stringByAppendingPathComponent(file), error: &error) {
println("ERROR | while deleting file: \(error)")
}
}
}

// main
let fm : NSFileManager = NSFileManager()
let directories = ["Desktop","Downloads"]
for dir in directories {
let path : String = NSHomeDirectory().stringByAppendingPathComponent(dir)
processDirectory(path, fm)
}

  1. Apple Computer. Swift Programming Language. https://developer.apple.com/swift/ Link

  2. qfx files are Quicken files. When I download transactions from financial institutions, these are the files that get deposited everywhere. I don’t like having them sitting around; so I wrote this admin tool to weed them out periodically. It’s set to run as a cron job launch agent.

Practicing for accuracy

Noa Kageyama, a Julliard-trained violinist and performance psychologist, writes a crazy-good blog called “The Bulletproof Musician”. I’ve tons of good tips from his blog; but I just ran across a post about practicing for accuracy.[1] He writes:

“But on some level we are also uneasy. Deep down we hope that it sticks, but we know from experience that it probably won’t. That the nice flow we got into, the level of playing we reached by the 40th repetition is not stable – and it’s probably not going to sound quite so flawless at our lesson or our jury in two weeks.”

and

“You run things ad nauseum to try to build up your confidence and keep everything “in your fingers,” and convince yourself that you can trust everything to work out ok when the moment comes.”

I’ve been perceiving that lately at the piano with a performance coming up shortly. It’s sense of confidence about my level of ability when I’m actually at the instrument; but as soon as I step away, I have a feeling that it’s going to slip away. It has me constantly sensing that I need to go back to the practice room to verify that I really have it in the fingers.

The solution (or rather, one of the solutions) is to apply variable practice. Instead of practicing at the same tempo or in the same way, one should vary the tempo above and below the performance target. He bases his recommendation on a study of children learning to accurately toss beanbags from a distance. Children who practiced tossing from variable distances were more accurate following a 12 week training period than those who only practiced at the final test target distance.

Cool. Reminds me over-under intervals that I’ve used in training on the bike.


  1. Kageyama, N. A Practice Strategy That Will Help You Play More Accurately When It Counts. Retrieved from http://www.bulletproofmusician.com/a-practice-strategy-that-will-help-you-play-more-accurately-when-it-counts Link

Effective metronome practice

Metronome anxiety

I grew up hating the metronome. The target of my disaffection was an old wooden Seth Thomas metronome that sat atop the upright piano in my parents’ house.

My teachers would urge me to solve problems with tempo, evenness, and velocity with slow metronome-guided practice. I’d give it a few tries and abandon it. During lessons, if the metronome started, I’d seize-up with anxiety. I suspect that metronome axiety is more common than teachers appreciate. A question in a piano practice forum captures the feeling precisely:

“Please advise on the metronome usage. I hate the thing! With the first sound of it I can feel my back and neck muscles tense up. How is one able to listen for the beat, concentrate on the notes, and technique for playing them, all at the same time.” [1]

I think there is a sense of being left behind when the metronome starts. If a passage is difficult, perhaps the fingering will get bungled and the metronome will keep going as if taunting the musician. Impatience is also a factor. We often don’t want to admit that achieving velocity and even execution is difficult and that it takes time. The metronome reveals that plainly to us. Whatever the cause, anxiety about the metronome is probably common. And sadly, unless the player overcomes it, he is robbed of an important tool for improving technique. When I began to play more chamber music 20 years ago, I found that I couldn’t mesh complex parts effectively without learning to play with more refined, even technique. Little by little I learned to live with the metronome and use it more effectively.

Choice of metronome

Personally, I regard the drum machine type metronomes useless for serious practice. Complex, accented rhythms are not what we need for practice. I can’t use the old pyramidal Maelzel metronomes because I constantly suspect their evenness. After several metronomes, I’ve finally found a model that I actually enjoy using, the Intelli IMT301. It’s very intuitive; and there’s no wasted functionality. (I’m not planning on trying to practice against a Bossa Nova rhythm.) This metronome is probably intended for string players; and we also use it for that too. Mostly I like it because it’s loud. I have no difficulty hearing it even when we use it in ensemble rehearsals. One minor critique is that the speaker is on the back. If you place the metronome horizontally on a surface or directly against a music stand, the sound is muffled. At the piano, I place it on the music desk upright but reclined at a slightly more acute angle than the stand so that the speaker isn’t occluded. When practicing the violin, I have it velcro’d to the top of the stand, again, so that the speaker isn’t obstructed.

I don’t like smartphone-based metronomes. None of the ones that I’ve tried have enough volume. Some have obvious issues with user experience. For example, there’s a Steinway metronome app that uses a faux analog rotary dial control to change the tempo setting. Because of the way people hold cell phones, the right thumb is used to move the control. But the thumb reaching across the phone from left to right obscures the tempo reading in the center of the dial.

Metronome practice for velocity

In the first movement of the Beethoven Piano Trio Op. 1 No. 3, there is a moderately difficult fast sixteenth note run that appears three times in two different forms:

beethoven trio

Just ignore the fingering. Even with the best fingering, at the tempo marking “Allegro con brio”, it’s fast. It also doesn’t conform to any particular known scale. It just weaves around the violin and cello parts in an agitated way. There are several places in these passages, where the second finger has to be passed over the thumb with an interval of a third. My target is about 140 to a quarter note; so how should I begin to attack this passage to achieve the desired performance tempo?

First, the choice of fingering has to be worked out before reaching for the metronome. Starting to practice with the metronome before all of the fingering choices have been evaluated will be frustrating and will lead to more metronome anxiety. At a minimum, it’s ineffective. Take time to slowly develop the fingering and write it into the score. Consider the fingering in the context of what comes before and after the passage in question. At this point, the metronome isn’t helpful; this phase is about discovery - finding what fingering works.

After you’ve found the right fingering[2], then you are ready for slow practice. In this case, since my target is 140 to the quarter note, I would start at under 70. If you can play the passage perfectly in a relaxed way with all of the decided-on fingerings, then you can advance the metronome by 5 beats per minute. I keep repeating this process, increasing the tempo at 5 bpm increments. I stop increasing when I feel the first sign of tension in the hand, wrist, or forearm. This is the point where you should dial the metronome back by 10 bpm.

Beginning from 10 bpm below the point where tension first developed, you can slowly increase the tempo by 2-4 beats per minute. You may also begin to experience diminishing returns due to fatigue. If you begin to sense fatigue, it’s best to stop and move on to a less demanding passage or a passage with different technical requirements.

I keep track of how the tempi are progressing so that I can begin each practice session with the right tempo. At the next session, I may start a little faster than 70 bpm and advance in 10 bpm up to the point where tension developed in the last session. From that point on, I will advance more slowly to the tension point, then back off again. In no case do I attempt to push the tempo beyond the point where I can play the passage accurately or the point where muscular tension develops. By practicing intentionally in this way, I can make no wasted effort in attempting to get the passage up to performance tempo and I reduce the likelihood that I’ll injure myself.

Metronome practice for evenness

Of course velocity is not the only concern. We want to be able to play passages at the right tempo and without any unmarked accents. For piano, we’re concerned about dynamic and agogic[3] accents. In other instruments, tonic accents have to be considered. In any case, these accents, if unmarked and unintended impeded the evenness of a passage at whatever tempo the performer can play.

The metronome, of course, can help with this goal also. In an effort to remove unwanted accents, I may start with an even lower metronome mark and progress more slowly, drawing my focus on making smooth transitions, especially finger crossings. With the metronome, we have to be careful though, not to actually introduce a dynamic accent on the beat in an effort to stay synchronized with it. I fight this constantly.

Other metronome tips

  • I like to turn on the feature that accentuates the first beat of each measure. For some reason I feel less of the metronome anxiety when a hear a clear downbeat.
  • There’s a risk of over-practicing while inching up the tempo. Working for too long with the metronome can lead you to practice a spot excessively. I’ve found the clue there is in the diminishing returns from elevating the tempo and in the feeling of tension. I make a commitment with myself to stop at that point.
  • Scales are a good way to gain experience with the metronome.

  1. Tech 5. “metronome hatred” Piano World Forums 27 July, 2012 Link

  2. By “right fingering” I mean the fingering that works for you.

  3. Agogic accents are those that a temporal - delays in onset or offset of a note, for example.