Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.