Named Types vs Compound Types

Swift Functions as Types

Named Types are those which are defined and identified by the name that they’re given. Classes, structs, enums, and protocols fit this category of Type.

Initializing instances of Types and using their properties and methods, passing them around to functions that require parameters of those Types, or setting them as values to properties of other Types are all pretty standard thoughts that come to mind when using named Types.

Compound Types (Functions, Tuples)

Compound Types, on the other hand, don’t have names. Rather, they have “signatures” that define and identify them as Types. Swift has two compound Types: functions and tuples.

Now I know what you might be thinking: “Functions have names!”

Indeed many do. But when we’re thinking about them in terms of their Type-ness. We’ve got to go beyond the name to the function’s “signature” characteristics.

The name of a function (or tuple, since they can be type-aliased) is simply how we refer to the function in code to execute it or pass it around as an argument.

The “signature” of the function, however, is the part that characterizes the function as a Type.

Function Types

What exactly makes up a function’s Type-ness or “signature” as I’ve been calling it? Two things:

The Type(s) of its parameters
The Type that the function returns

Given:

“What is the generateStarWarsName function’s Type?”,

answer: “generateStarWarsName is a function Type that has three parameters, the first two of Type String, the last of Type Int, and that returns a value of Type String.”

Given the above generateStarWarsName function, we could notate its Type as follows:
(String, String, Int) -> String

Remove “generateStarWarsName”, “firstName: “, “lastName: “, and “birthYear: ” and you’re left with that raw Type information. What remains is the function’s Type notation.

It tells you (and the Swift compiler) everything you need to know to be able identify the Type of that function… it’s “signature”, if you will.

examples:

func returnHelloString() -> String {}, () -> String
func sayHello() {}, () -> Void
func complimentMe(name: String) -> String {}, (String) -> String
func countToTen() {}, () -> Void
func addInts(first: Int, second: Int) -> Int {}, (Int, Int) -> Int
func fadeIn(duration: NSTimeInterval, delay: NSTimeInterval, completion: (Bool) -> Void){}, (NSTimeInterval, NSTimeInterval, (Bool)->Void) -> Void