Swift Function Lists

I’m going to need to make heavy use of Swift function lists for what I intend to do with MIDI. I’m very familiar with C proc ptrs so the basics of this don’t scare me, but Swift syntax is different enough that I thought I should make a little test app to get familiar with how this all is done.

Also, because I don’t need a GUI, I thought I’d make a command-line Swift app. Turns out this is a lot like a sandbox, since there’s no main().

Anyway, here’s the code, first with an explicit function list arg, and then the same basic thing using a variadic parameter list.

import Foundation

func doFrench(name: String) -> String {
	return "Bonjour " + name
}

func doEnglish(name: String) -> String {
	return "Hello " + name
}

func doSpanish(name: String) -> String {
	return "Hola " + name
}

func doGerman(name: String) -> String {
	return "Hallo " + name
}

func doHellos(name: String, helloProcs: [(String) -> String]) {
	for p in helloProcs {
		let s = p(name)
		Swift.print(s)
	}
}

let hellos = [doFrench, doEnglish, doSpanish, doGerman]

Swift.print("What is your name? ", terminator: "")
let name = Swift.readLine(stripNewline: true)
doHellos(name!, helloProcs: hellos)

func doHellos2(name: String, helloProcs: (String) -> String...)
{
	for p in helloProcs {
		let s = p(name)
		Swift.print(s)
	}
}

Swift.print("What is your other name? ", terminator: "")
let name2 = Swift.readLine(stripNewline: true)
doHellos2(name2!, helloProcs: doFrench, doGerman, doSpanish, doEnglish)

I think it’s pretty self-explanatory. Example input/output:

What is your name? Tendonitis
Bonjour Tendonitis
Hello Tendonitis
Hola Tendonitis
Hallo Tendonitis
What is your other name? Malaria
Bonjour Malaria
Hallo Malaria
Hola Malaria
Hello Malaria
Program ended with exit code: 0

Using the already written doHellos2() I did the same thing with closures instead of functions:

Swift.print("What is your last name? ", terminator: "")
let name3 = Swift.readLine(stripNewline: true)

doHellos2(name3!, helloProcs: { s in "Hello " + s },
							  { s in "Hallo " + s },
							  { s in "Bonjour " + s },
							  { s in "Hola " + s })

This works like you would expect.

Leave a Reply

Your email address will not be published. Required fields are marked *