First-class functions
In the Function types section of this chapter, we saw that we can define function types and store and pass functions around. In practice, this means that Swift treats functions as values. To explain this, we will need to examine a couple of examples:
let name: String = "Grace"
In this code example, we create a constant of the String
type name
and store a value ("Grace")
into it.
When we define a function, we need to specify the type of parameter, as follows:
func sayHello(name: String) { print("Hello, \(name)") }
In this example, our name
parameter is of the String
type. This parameter could be any other value type or reference type. Simply, it could be Int
, Double
, Dictionary
, Array
, Set
, or it could be an object type such as an instance of class
, struct
, or enum
.
Now, let's call this function:
sayHello(name: "Your name") // or sayHello(name: name)
Here, we pass a value for this parameter. In other words, we pass one of the previously mentioned types with their respective...