function
- Functions are chunks of code we’ve split off from the rest of program
- given a name so we can refer to them easier
Let’s say we want to print this lines of string on the screen. It’s okay to use if this is on only one screen. But what if it’s on multiple pages?
- Function allows us to pull out the code, give it a name, and run it whenever and whereever.
() are used with functions.
When we create a function, () are used.
or, When we call the function: ask swift to run the code
() are known as the function’s call site: “a place where a function is called”
We add configuration options for our functions
We get to pass data that customizes the way the function works
isMultiple(of:) If it didn’t allow any kind of customization in call site, what is it multiple of?
Yes, there are functions that doesn’t require configuration options, like isOdd() or isEven().
By writing (of: 2) , we can check for multiple of any other numbers.
We were rolling virtual dice in Loop, While & Skip tutorial with a code like this:
by writing (in: 1...20), we control over the range of our random numbers.
without it, random integer of what?
(number: Int) inside the parentheses is called parameter.
- Inside the
(),number:is used like any other constant containsInt
- We need to write the parameter name as part of the function call.
- Naming gets more important when we have multiple parameters.
(number: 5, end: 20) inside this parentheses is called argument.
We have both parameters and arguments: one is a placeholder the other is an actual value, so if you ever forget which is which just remember Parameter/Placeholder, Argument/Actual Value.
- But we use “parameter” for both, or “argument” for both. it doesn’t matter.
When we run the fuction, we have to write the argument in order they were listed when it was created.
Return values from functions
Functions can also send data back.
import Cococa includes a variety of mathematical functions, sqrt()
sqrt() function accepts one parameter (Int), it will do the work and send back the data
- If I want to return my own value from a function need to do two things
- Write an arrow then a “data type” before opening brace, telling Swift what kind of data will get sent back
- Use the return keyword to send back data
- Function must return an integer
func rollDice() -> Int {}
- The actual value is sent back with the
returnkeyword.
Now we can use rollDice() in lots of places across the program.
Hint: use sorted() to get a new string back with all the letters in alphabetical orders
Hint: use == to compare them to see if their letters are the same
Hint: make function names areLettersIdentical
Let’s break down
- It creates a new function called
areLettersIdentical()
- The functions accepts two string parameters
(string1: string, string2: string)
- The function says it returns a
Bool, at this point we must return either true of false.
- Use
==to compare strings → if they are same, it will return true else false.
We can skip those temporary constants first and second and just compare the results of sorted() directly.
If there is only one line of code, we can remove return
So, that’s a function called pythagoras(), that accepts two Double parameters and returns another Double. Inside it squares a and b, adds them together, then passes that into sqrt() and sends back the result.
That function can also be boiled down to a single line, and have its return keyword removed – give it a try.
Return multiple values from functions
Write an arrow and a data type to return a single value from a function
Use an array to return two or more values from a function
It’s hard to remember what user[0] and user[1] are.
- It can be problematic to adjust the data in that array in future
We can use #dictionary , but it has its own problems.
- We still need to provide default value
default: "Anonymous"
We can use a solution in the form of #tuples.
Tuples let us put multiple pieces of data into a single variable
Unlike those other options tuples have a fixed size and can have a variety of data types.
- Return type is now
(firstName: String, lastName: String), a tuple containing two strings.
- Names in tuple aren’t in quotes. Opposed to the kind of arbitrary keys in dictionary.
- Send back a tuple containing all the elements we promised.
(firstNmae: "Taylor", lastName: "Swift)
- Can read the tuple’s values using the key name when we call
getUser().
1. In a dictionary, we have to provide a default value because Swift can’t be sure if the value is going to be there.
2. Swift knows ahead of time that values in tuple will be always available.
3. We access values using
user.firstName, which isn’t string, so there’s no chance of typos.4. Dictionary might contain hundreds of other values alongside
"firstName" but tuple can’t There are three other things it’s important to know when using tuples.
- We don’t need to repeat names when using
return, because Swift already know the names we are giving each item in tuple.
- Sometimes, we’ll find given tuple’s elements don’t have names. We can access the elements using numerical indices.
The document provides eight key pieces of advice for those starting their programming journey: 1) Technology will change, so don't get stuck on one language or platform. 2) You won't remember everything you learn, and that's okay. 3) A computer science degree isn't necessary, but understanding CS fundamentals is important. 4) Continuous learning is part of the job. 5) Learn how to learn effectively. 6) A basic understanding of mathematics can be beneficial. 7) Resilience is crucial in overcoming challenges. 8) Programming involves more than just coding; interpersonal skills are also important. A bonus tip suggests investing in a mechanical keyboard.