Functions
A function is a block of organized and reusable code used to perform a single, related task/action.
Functions are also referred to as methods, procedures, or sub-routines.
On top of that, functions are always part of a class and can return back values if needed.
Simple Function
func simpleExample():
pass
In this case, the simpleExample()
funciton does nothing.
The pass
keyword does nothing except preventing the compiler from showing the empty function soft error.
The pass
keyword can also be used in loops to avoid the empty loop error.
Function with Parameters
You can pass values into a function through the function’s parameter (the parenthesis):
func simpleExample(parameter):
pass
Function with Specific Data Type Parameters
You can also force a single data type onto a parameter value:
func simpleExample(parameter: String):
pass
In this case, our simpleExample
function parameter can only take in string values.
You can also set the default value of a parameter:
func simpleExample(parameter := "default value"):
pass
In this case, we would like our parameter to take in only string values, and if none is provided the default value will be the literal string “default value”.
Keep in mind that the :=
infers the data type.
Function with Specified Return Type
You can declare what type of value is returned from the function using the ->
symbol and the return
keyword:
void
The void
data type specifies that your function does not return back anything.
When using the void
data type, you do not have to provide the return
keyword.
func simpleExample() -> void:
return
int
func simpleExample() -> int:
return 10
float
func simpleExample() -> float:
return 2.13
bool
func simpleExample() -> bool:
return true
Function Name Best Practices
Stay consistent with naming your functions.
I use camelCases for small projects.
# camelCase
func simpleExample() -> bool:
return true
For bigger ones, consider using snake_case:
# snake_case
func simple_example() -> bool:
return true