In this chapter, we will look at the basics of function declaration in Swift, and we'll leave the more advanced features until Chapter 5, Advanced Swift.
To define a function in Swift, we use the following syntax:
func functionName(argument: argumentType) -> returnType { // code }
We can define a function that takes no arguments and returns no value as follows:
func printDate() { print(Date()) }
Note that it is not necessary to declare a Void
return value, though we may do so if we choose.
We would call that function as follows:
printDate()
Arguments to the function are supplied in the parentheses following the function name, in the form argName: argType
; if there are more than one, they are separated by commas:
func printPoint(x: Int, y:Int) { print(x, y) }
We would call that function as follows:
printPoint(x: 11, y: 59)
The argument value(s) must be preceded by the argument name(s), as can be seen previously.