Swift Programming - Zero To Hero - Part Seven

Introduction 
   
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 
  1. func functionName(){  
  2.   
  3. // Some Operation   
  4.   
  5. // Block of Codes  
  6.   
  7. }  
 Example  
  1. func firstFunction(){  
  2.   
  3. print("Hello, My First Function in Swift")  
  4. }  
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,  
  1. firstFunction()  
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. 
 
Syntax  
  1. func functionName(paramenterName: Datatype){  
  2. }  
 Example 
  1. func firstFunction(values: string){  
  2.   
  3. }  
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. 
  1. 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.
 
Multiple Parameters 
 
A Function can have more than one parameter. For this you have to pass multiple arguments.
 
Syntax 
  1. func functionName(argumentName1: type , argumentName2: type){  
  2.   
  3. // Code Blocks  
  4.   
  5. }  
 Example  
  1. func firstFunction(values: string, names:string){  
  2.   
  3. }  
 In the above given example, values and names are the arguments of firstFunction().
 
Conclusion  
 
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.


Similar Articles