Functions
#code-smell #function #return #tuples #dictionary #method
Overview
Benefits of using Functions
Clearer code
Breaking big chunks of code into small pieces, so that you read and follow the code easily
Reusability in other functions, therefore you can write clearer code
Ease of change
When used in multiple places and other big functions, you change the behavior of the function from a place with ease
Things to Consider
Not to add more than 6 parameters
Splitting up into smaller functions for sake of readability
Whether those parameters are related to each other
Throwing Data back
If you want to return your own value from a function, you need to do two things:
Write an arrow then a data type before your function’s opening brace, which tells Swift what kind of data will get sent back.
Use the
returnkeyword to send back your data.
Copying Functions
When you copy a function you do not use parenthesis ()
Source: HWS,
When copying functions parameters will not come externally??? #learn
Removing Parameter Name
No difference in result at all.
Defining a Default Value for a Parameter
Source: HWS,
Checking Errors
If a Function may throw an error, you must add error handling both to prevent crashing the app and to clarify the cause.
But keep in mind that adding a throw to function may cause many other problems. So it is better not to add them at the beginning. By the time you become familiar with the app itself and the throw mechanism, you will ad them carefully.
Source: HWS,
Handling Function Failure with Optionals
If you only care about whether the function works or not, try may help. Otherwise do not use it.
If you want to know what those error are, and handle them uniquely, do not use "try?", but use do-catch-try block instead.
Source: HWS,
Methods
When Functions belong to Structs, they become Methods.
Sources
Mutating Function
Gives you ability to change a constant in a struct (HWS / 100days / 10).
// But why to change it? If we need to change it afterwards why we not define it as a var? #learn
Example 1: Resetting the the value set to its defaults
Sources
Videos
Articles / Documents
Functions as Parameters
Source: https://www.hackingwithswift.com/quick-start/beginners/how-to-accept-functions-as-parameters
Sample Codes


Sources
Videos
Articles / Documents
Last updated
Was this helpful?