- Functions are chunks of code we’ve split off from the rest of program
- given a name so we can refer to them easier
print("Welcome to my app!")
print("By default This prints out a conversion")
print("chart from centimeters to inches, but you")
print("can also set a custom range if you want.")
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.
func showWelcome() {
print("Welcome to my app!")
print("By default This prints out a conversion")
print("chart from centimeters to inches, but you")
print("can also set a custom range if you want.")
}
()
are used with functions.
When we create a function, ()
are used.
or, When we call the function: ask swift to run the code
showWelcome()
()
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
let number = 139
if number.isMultiple(of: 2) {
print("Even")
} else {
print("Odd")
}
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:
let roll = Int.random(in: 1...20)
by writing (in: 1...20)
, we control over the range of our random numbers.
without it, random integer of what?
func printTimesTables(number: Int){
for i in 1...12{
print("\(i) x \(number) is \(i * number)")
}
}
printTimesTables(number :5)
(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.
func printTimesTables(number: Int, end: Int){
for i in 1...end{
print("\(i) x \(number) is \(i * number)")
}
}
printTimesTable(number: 5, end: 20)
- Naming gets more important when we have multiple parameters.
printTimesTable(number: 5, end: 20)
(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
import Cocoa
let root = sqrt(169)
print(root)
- 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
func rollDice() -> Int {
return Int.random(in: 1...6)
}
let result = rollDice()
print(result)
- Function must return an integer
func rollDice() -> Int {}
- The actual value is sent back with the
return
keyword.
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
func arelettersIdentical(string1: string, string2: string) -> Bool {
let first = string1.sorted()
let second = string2.sorted()
return first == second
}
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.
func areLettersIdentical(string1: String, string2: String) -> Bool {
return string1.sorted() == string2.sorted()
}
If there is only one line of code, we can remove return
func areLettersIdentical(string1: String, string2: String) -> Bool{
string1.sorted() == string2.sorted()
}
import Cocoa
func pythagoras(a: Double, b: Double) -> Double {
let c = (a*a) + (b*b)
let result = sqrt(c)
return result
}
let c = pythagoras(a: 3.4, b: 8.5)
print(c)
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.
import Cocoa
func pythagoras(a: Double, b: Double) -> Double {
return sqrt(a * a + b * b)
}
let c = pythagoras(a: 2.0, b: 3.0)
print(c)
Return multiple values from functions
Write an arrow and a data type to return a single value from a function
func isUppercase(string: String) -> Bool {
string == string.uppercased()
}
Use an array to return two or more values from a function
func getUser() -> [String] {
("Taylor", "Swift")
}
let user = getUser()
print("Name: \(user[0]) \(user[1])")
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.
func getUser() -> [String: String] {
[
"firstName": "Taylor",
"lastName": "Swift"
]
}
let user = getUser()
print("Name: \(user["firstName", default: "Anonymous"])
\(user["lastName", default: "Anonymouse"])")
- 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.
func getUser() -> (firstName: String, lastName: String) {
(firstName: "Taylor", lastName: "Swift")
}
let user = getUser()
print("Name: \(user.firstName) \(user.lastName)")
- 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’tThere 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.
func getUser() -> (firstName: String, lastName: String) {
("Taylor", "Swift")
}
let user = getUser()
print("Name: \(user.firstName) \(user.lastName)
- Sometimes, we’ll find given tuple’s elements don’t have names. We can access the elements using numerical indices.
func getUser() -> (String, String) {
("Taylor", "Swift")
}
let user = getUser()
print("Name: \(user.0) \(user.1)")
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.