This is part Seven of the Swift article series "Swift Programming - Zero to Hero". You can read my previous article from the below links,
- http://www.c-sharpcorner.com/article/swift-programming-zero-to-hero-part-six/
In this article we will be learning about Functions in Swift.
Functions
Functions are blocks of code, that can be executed whenever it's needed. In Swift programming, the function begins with the keyword as func, followed by function name.
Syntax
- func firstFunction(){
-
- print("Hello, My First Function in Swift")
- }
In the above given example,
firstFunction() is a function with firstFunction as function name and
func as keyword. As in general programming languages, the name of function is followed by the pair of parentheses that contains functions parameters - the input to the function.
The block of codes are wrapped in a pair of curly braces. From the above example, firstFunction() function contains a print statement. This is how the Swift Program's Functions looks like.
Now we can invoke the function by typing the name of functon , followed by parenttheses as,
Functions with Parameters
We can provide Inputs to a function. Those inputs are known as Parameters of function or simply parameter. Those input values are used in the function's body.
- func firstFunction(values: string){
-
- }
In the above given example, value is the parameter name with data type of string. The Parameters are wrapped by parentheses that follow the function name. The name of parameter is followed by a colon (:) and the paramenter's type.
Invoking the function is very simple as we saw before. Here you have to pass the argument.
- firstFunction(values: "My First Function")
In Swift, parameters are the values specified in the function's definition, while arguments are the values passed to the function when it is invoked.
In this article, we have learned briefly about functions in Swift. In my next article we will learn about return types and tuples in detail and also some good examples in functions. Hope this article was very useful. Kindly give your feedback in the comments section.