Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift Functions and Optionals Functions Syntax and Parameters

why do we need functions in swift, and what is an easy to understand definition of a func, or function?

i need to know, please help

3 Answers

A function is simply a convenient way for you to be able to write a piece of code which carries out a task and allows you to reuse that code by calling the function from different places in your program.

Digvijay Jaiswal
Digvijay Jaiswal
5,565 Points

In short, due to DRY (Don't Repeat Yourself) principle. would you prefer to write the same code 100 times?

In the Swift programming language guide, functions are defined as: "self-contained chunks of code that perform a specific task. You give a function a name that identifies what it does, and this name is used to β€œcall” the function to perform its task when needed".

You don't have to think too hard every time you do some mundane task, like making a sandwich, because your brain has automated it. It's the same with functions. They automate a particular task that you will need to preform several times over without thinking too hard, or taking up too much space as chunks of code.