Today we learn about functions used in swift. Functions are self-contained chunks of code that perform a specific task.Swift functions contain parameter type and its return types.
Function Definition
Function Definition
In Swift, a function is defined by the "func" keyword. When a function is newly defined, it may take one or several values as input 'parameters' to the function and it will process the functions in the main body and pass back the values to the functions as output 'return types'.
Syntax
1) Function without parameter and without return type
Explation:
func funcName (Parameters) -> returntype {
//Statements
return parameters
}
1) Function without parameter and without return type
func learnSwift(){
print("Hello Swift")
}
This function having no arguments and return type. func is keyword used before a function name.
"learnSwift" is the function name.
Default Parameter Values :
How to call function in Swift:
Now open your xcode and create a new playground file. After function declaration now its time to call your function.
2) Function with parameter and having no return type:
3) Function with multiple parameters and having no return type :
4) Function with paramter and having return type:
Here learnSwift function having String return type. myCurrentVersion is returned as String datatype.
Default Parameter Values :
Here "version" parameter is declared as default parameter value with "3.0"
Variadic Parameters
A variadic parameter accepts zero or more values of a specified type. You use a variadic parameter to specify that the parameter can be passed a varying number of input values when the function is called. Write variadic parameters by inserting three period characters (...) after the parameter’s type name.Variadic Parameters
Note*
A function may have at most one variadic parameter.
In-Out Parameters :
You write an in-out parameter by placing the inout keyword right before a parameter’s type.
Note* In-out parameters cannot have default values, and variadic parameters cannot be marked as inout.
To modify the function parameters we can use in-out parameter .
Conclusion:
All code in this post was tested against a playground in Xcode 8.
Today we learn about functions used in swift language.Since functions are so important to programming, they definitely need a lot of flexibility to do their job well.
I hope you found this article helpful. If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps. Of course, if you have any questions, don’t hesitate to contact me .Please add your comments to make blog more informative.
Thanks!