Swift — Function

Similar to the mathematic functions

  • Function can define a group of code which could be several lines or fulfill specific function.
  • By calling function can execute the code in function
  • “Print” can show the result of function
print("Peter")
print(100)

Why do we need function?

  • if there is no function, we need to calculate the similar function once again and again, such as…
var sum = 0 
for i in 1...100 {
sum = sum + i
}
var sum = 0 
for i in 1...200 {
sum = sum + 1
}

Define and call Function

Define: func + Name + () + {Code}

Call: function name + ()

Function without other parameters

func addToNumeber100() {
var sum = 0
for i in 1...100 {
sum = sum + i
}
}
func addToNumber200() {
var sum = 0
for i in 1...200 {
sum = sum + i
}
}

Function with parameters

Name of parameter + : + Type

func addToNumber(number:Int){
var sum = 0
for i in 1...number {
sum = sum + i
}
}
addToNumber(number:100)

More than one parameters

func addToNumber(startNumber:Int, endNumber:Int) {
var sum = 0
for i in startNumber...endNumber {
sum = sum + i
}
}
addToNumber(startNumber:10, endNumber:100)

External name & internal name of function

  • internal name: define in function
  • external name: using when call the function
func eat (foodName name name:String, foodPrice price:Int) {
let message = "花了$\(price)吃\(name)"
}
eat(foodName:"珍奶", foodPrice:700)

Delete the automated name of parameter _

func eat(name:String, _ price:Int){
}
eat(name:"milk", 300)

Return data

fun addToNumber(startNumebr:Int, endNumber:Int) -> Int {
var sum = 0
for i in startNumber...endNumber {
sum = sum + i
}
return sum
}
var sum1 = addToNumber(startNumber:1, endNumber:100)
var sum2 = addToNumber(startNumber:200, endNumber:300)
var sum3 = sum1 + sum2

Practice

Function with parameters in function

Important check

  • the number of parameter
  • the type of parameter
  • the type of return
Show your support

Clapping shows how much you appreciated Hsin-Hua Lin’s story.