W1205 Function Introduction

From Coder Merlin
Revision as of 22:26, 13 November 2019 by Chukwuemeka-tinashe (talk | contribs) (Created page with "thumb|right|link=|Tektronix FG 504 Function generator with DC 503 Universal Counter == Prerequis...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
Tektronix FG 504 Function generator with DC 503 Universal Counter

Prerequisites[edit]

Introduction[edit]

Functions enable us to package a sequence of statements that we could easily reuse whenever desired. Functions can be used to break up a larger program into smaller, more easily understood units.

The code contained within a function is known as the body of the function. Some functions, similar to the way we use functions in algebra, expect one or more values to be provided by the calling program when it invokes the function. The function declares placeholders, called parameters for each value required. The type of value must also be specified. When the function is later invoked, the calling program specifies the actual arguments which must match the declared parameters.

Some functions may also return a value back to the caller (again, similar to the way we think of functions in algebra). In many cases functions will indeed behave as algebraic functions, where the returned value is dependent entirely on the argument(s).

Function Invocation[edit]

Activating (or calling) a function is formally termed function invocation. An example of invoking an algebraic-like function is:

let xCoordinate = cos(Double.pi * 2)

In this case, the name of the function is "cos" taking a single argument of type Double and returning a Double. In this case, the function has no side-effects, that is, it does not in anyway modify any data structures elsewhere, it simply returns a value. In other cases, however, it may be desirable to perform some side effect.

Side Effects[edit]

In the above case, the function has no side-effects, that is, it does not in anyway modify any data structures elsewhere, it simply returns a value. In other cases, however, it may be desirable to perform some side effect. For example, functions are available to open a file for writing or to retrieve a web page specified by a URL parameter.

Anatomy of a Swift Function Declaration[edit]

Key Concepts[edit]

Exercises[edit]

References[edit]