About Swift Functions

From Coder Merlin
Revision as of 22:23, 20 February 2019 by Chukwuemeka-tinashe (talk | contribs) (Created page with "== Parameters, Arguments, and Labels == Consider the following function definition: <syntaxhighlight lang="swift" line> func addTwoNumbers(a:Int, b:Int) -> Int { return a...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Parameters, Arguments, and Labels[edit]

Consider the following function definition:

func addTwoNumbers(a:Int, b:Int) -> Int {
    return a + b
}

Examine line 1, specifically the parameter list, a:Int, b:Int. "a" and "b" are termed the formal parameters to the function. Within the function body these formal parameters take on the value as specified by the caller when the function is invoked. By default, "a" and "b" become the external labels for the caller.

Now consider the following function invocation:

addTwoNumbers(a:7, b:22)

Examine line 4, specifically the argument list, a:7, b:22. In this case "a" and "b" are the external labels, and the argument value of 7 is used for the parameter labeled by "a" and the value of 22 is used for the parameter labeled by "b".

It's important to understand that this relationship (label first, a semicolon, then the argument value) holds regardless of the actual value specified. Consider:

let a = 7
let b = 22
addTwoNumbers(a:a, b:b)

Examine line 5 and line 6. Each defines an Integer constant. The constant "a" is assigned the value of 7, and the constant "b" is assigned the value of 22. Line 7 then invokes the function "addTwoNumbers" with two arguments. The argument list is a:a, b:b. The first "a" is the argument label, the second "a" is the argument value, a constant named "a" with the value of 7. Likewise, the first "b" is the argument label, the second "b" is the argument value, a constant named "b" with the value of 22.

Key Concepts[edit]

  • The parameter list is the list of constants (by default) in the function header. They are sometimes called formal parameters.
  • The value of each constant is determined by the caller when the function is invoked. The caller specifies an argument list; these arguments are sometimes called the actual parameters.
  • The argument list is specified by comma separated pairs of a label followed by the argument value.