When you define a function, you can define one or more values that have a name and type, as input to the function (called a parameter, parameters), or you can define some type of value as the output of the function execution end (called the return type).
Each function has a function name that describes the task that the function performs. To use a function, you "call" with the function name and pass it a matching input value (called an argument, arguments). The arguments for a function must match the order of the parameters in the Function argument table.
The function in the following example "greetingForPerson"
is called because the function uses the name of a person as input and returns the greeting to the person. To accomplish this task, you define an input parameter-a personName
value called String
, and a return value that contains the type of the person's greeting String
:
func sayHello(personName: String) -> String { let greeting = "Hello, " + personName + "!" return greeting}
All of this information is summed up as a function definition and func
as a prefix. When you specify a function return type, it is represented by the return arrow ->
(a hyphen followed by a right angle bracket) followed by the name of the return type.
The definition describes what the function does, what it expects to receive, and what results it returns at the end of execution. Such a definition allows a function to be called in a clear way elsewhere:
println(sayHello("Anna"))// prints "Hello, Anna!"println(sayHello("Brian"))// prints "Hello, Brian!"
sayHello
when a function is called, it is passed to its argument of one type in parentheses String
. Because this function returns a String
value of type, it sayHello
can be included in println
the call to output the function's return value, as shown above.
In sayHello
the function body, a new named constant is defined greeting
String
, and personName
a simple greeting message is assigned. Then use return
the keyword to return the greeting. Once return greeting
called, the function ends its execution and returns greeting
the current value.
You can call multiple times with different input values sayHello
. The above example shows the result of the use "Anna"
and "Brian"
invocation, which returns different results, respectively.
To simplify the definition of this function, the creation and return of a greeting message can be written in one sentence:
func sayHelloAgain(personName: String) -> String { return "Hello again, " + personName + "!"}println(sayHelloAgain("Anna"))// prints "Hello again, Anna!"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Definition and invocation of Swift functions (defining and calling Functions)