+ 3

Why do we need functions? What about return? Swift

I don't understand what functions are meant for. What makes it hard to use sets or arrays only? Why do we need return in functions? What do we get by using it. Please explain. If possible please give examples. Thank you very much!

25th Jun 2019, 8:09 PM
the ы
the ы - avatar
5 Answers
+ 6
Functions are used to make your code concise so that you don't have to repeatedly write the same steps over and over again. The return keyword is used to come back to the point in the code where the function was called from.
25th Jun 2019, 8:30 PM
Sonic
Sonic - avatar
+ 2
The main purpose of functions is so that you don't have to constantly rewrite the exact same code multiple times throughout your program. A good rule of thumb is if you find yourself writing the same thing twice, create a function for it. This will cut down on the size and lines of code that has to be written, which means better performance and less time to accomplish something. Since a function is performing a particular task, if it is returning data to another part of the program, you use a return in the function. If it is not returning data, that's when you often see the use of 'void' - it doesn't need to return data but simply perform the task. I'm not familiar with Swift, and I've never even looked at Swift code, but I imagine it's the same basic concept. Hope that helps!
25th Jun 2019, 8:23 PM
AgentSmith
+ 2
To further touch on another good point that we didn't mention, imagine that you wrote the same stuff multiple times through your entire code... now imagine that you discover you did something wrong or in a way that you need to change it. If you had created a function, you'd only have to go and change it in one place. If you didn't create a function, you'd have to go to every single place that it's being used and change it there. It's a lot easier to fix something in one place and have it take effect everywhere that it was being used than trying to go all over your code fixing the same thing in multiple places.
25th Jun 2019, 8:33 PM
AgentSmith
+ 2
The first reason is reusability. Once function is defined it Can be used again and again...another aspect of reusabiltity is that a single function can be used in several different (separate) programs. The return keyword terminates the execution of the function and returns control to the calling function. A return statement can also return a value to the calling function.
26th Jun 2019, 1:37 AM
Natasha
Natasha - avatar
0
With return there's only one way to go on. If you choose something else it collapses. With functions there are loads of possible outcomes, like a tree diagram.
24th Dec 2019, 12:08 PM
Conor Walsh
Conor Walsh - avatar