More Functions Anyone?
- Nov 10, 2017
- 1 min read

Function with multiple parameters:
func invite(guest: String, rsvp: Bool) {
print("Dear \(guest), \n")
if rsvp {
print("See you tomorrow")
} else {
print("Please response quickly. \n")
}
print("Love, ")
print("Banana")
}
====
Let's remove argument label (_:)
====
Let's add custom argument label
func sayHello(to friend: String, from name: String) {
print("Hello \(friend) from \(name)")
}
sayHello(to: "Megan", from: "Natalie")
=====
func sendThankYou(to friend: String, for gift: String) {
print("Thank you \(friend) for the \(gift)")
}
sendThankYou(to: "Natalie", for: "Wallet")
====
func volumeOfBox (_ side1: Int, _ side2: Int, _ side3: Int) {
print("Volume of the box is \(side1 * side2 * side3)")
}
volumeOfBox(3, 4, 5)
=== Let's Return Value ===
func volumeOfBox (_ side1: Int, _ side2: Int, _ side3: Int)
-> Int {
let volume = side1 * side2 * side3
return volume
}
var box1 = volumeOfBox(2, 2, 2)
var box2 = volumeOfBox(2, 2, 2)
if box1 > box2 {
print("box 1 is bigger")
} else if box2 > box1 {
print("box2 is bigger")
} else {
print("box1 and box2 are same size")
}
=== Average ===
func averageOf(_ scores:[Int]) -> Int {
var sum = 0
for score in scores {
sum += score }
if scores.count > 0 {
return sum / scores.count
} else {
return 0
}
}
var averages = averageOf([1,2,3,4,5,6,7])
print("The average is \(averages)")
=== Homework ===
- Write 1 function to calculate an area of a rectangle and a perimeter of a rectangle, depending on the parameters the you pass into the function.
- Be creative!


































Comments