Swift has first-class functions and that opens up a lot of possibilities. In this post, we explore function types. We also cover named types and compound types.

What Are Function Types?

Each function in Swift has a type. When you hear the term type, you probably think of classes, structs, and enums. Classes, structs, and enums are named types. This makes sense because you can refer to the type by name. In this example, we define a class with name ViewController. We can use the name ViewController to refer to the type hence the term named type.

class ViewController: UIViewController {

}

Swift also defines types that don't have a name. Functions and tuples are examples of types that don't have a name. We refer to these types as compound types. As the name suggests, a compound type is composed of other types.

The ViewController class defines a function with name viewDidAppear(_:). What is the type of this function? The function has a compound type. It accepts one parameter of type Bool and it returns Void. That is the type of viewDidAppear(_:).

class ViewController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {

    }

}

What Is the Difference Between a Function and a Method?

You may be wondering why I refer to viewDidAppear(_:) as a function. Isn't viewDidAppear(_:) a method? That is correct, but every method is a function. A method is nothing more than a function that is associated with a type. In this example, viewDidAppear(_:) is associated with the ViewController class. Every method is a function, but not every function is a method.