Wednesday, November 22, 2017

Swift 4 Book I Chapter 6: Basics of Function

Chapter 6: Basics of Function

A function is a set of code that performs a specific task. We group such code into a function so that we can repeat the task again and again by calling the function.

Defining and Calling Function

To declare or define a function, we must know that there are basically 4 types of functions. They are:
  • Function with no parameter and return value
  • Function with parameter but no return value
  • Function with parameter and return value
  • Function with no parameter but have return value (Rare)

Of course we can have multiple parameter or return value but such function are more complex and it will be dealt with in a later chapter. For now, we will focus on the basics of function.

Defining and Call Function with no Parameters and Return Value

To declare a function, we must have a name. The syntax is as follows:

func <function_name>() {
<set_of_instructions>
}


Example:

func printHello() {
   
   print("Hello!")
   
}


To call the function, we just type the function name with brackets. Syntax is as follows:

<function_name>()

Example:

printHello()


Defining and Call Function with Parameters and no Return Value

To declare a function, we must have a name. We also need to include the parameters. The syntax is as follows:

func <function_name>(<parameter_name>:<datatype_parameter>) {
<set_of_instructions>
}


Example:

func printHelloWithName(name: String) {
   
   print("Hello! \(name), how are you?")
   
}


To call the function, we must include the input data with the correct data type in the brackets as define in the function. Syntax is as follows:

<function_name>(<input_data_mtached_datatype>)

Example:

printHelloWithName(name: "Steve")



Defining and Call Function with Parameters and Return Value

To declare a function, we must have a name, parameter and the datatype of return value. The syntax is as follows:

func <function_name>(<parameter_name>:<datatype_parameter>) -> <dataype_return_value> {
<set_of_instructions>
return <return_value>
}


Example:

func square(input: Int) -> Int {
   
       let answer = input * input
       return answer
   
}


We can simplified the above function to the following:

func square(input: Int) -> Int {
   
       return input * input
   
}


To call the function, we can call the function and at the same time assigned the return value to a constant. The syntax is as follows:

let/var <variable_name> = <function_name>(<input_data_mtached_datatype>)

Example:

let result1 = square(input: 2)
print("result 1 is \(result1)")

let result2 = square(input: 10)
print("result 2 is \(result2)")



Defining and Call Function with no Parameters but have Return Value

We can also have a function that produces a return but no input parameters. To declare such a function, we must have a name and the datatype of return value. The syntax is as follows:

func <function_name>( ) -> <dataype_return_value> {
<set_of_instructions>
return <return_value>
}

Such function is very rare. One of possible example is to extract current date. See example below.

Example:
import UIKit

func getCurrentDay() -> Int {
   let cd = Date()
   let calendar = Calendar.current
   let day = calendar.component(.day, from: cd)
   return day
}


To call the function, we can call the function and at the same time assigned the return value to a constant. The syntax is as follows:

let/var <variable_name> = <function_name>()

Example:

let today = getCurrentDay()

print(today)



Function in a Function

Calling Function in a Function

In the example above, we already call a function within our function. We can call a function within our function. In fact, that function may call another function. Let's examine the code above again:

import UIKit

func getCurrentDay() -> Int {
   let cd = Date()
   let calendar = Calendar.current
   let day = calendar.component(.day, from: cd)
   return day
}

UIKit is a library of prewritten code and function available for us to use. The function we are using is Date(). This function retrieve current date and time. We also use another function .component(.day, from: cd) to extract the day of the current date.

Nested Function

We can also create a function in a function. This is call a nested function.

Example:

import UIKit

func getDayOrMonth(choose:Int) -> Int {
   
   switch choose {
   case 1:
       func getCurrentDay() -> Int {
           let cd = Date()
           let calendar = Calendar.current
           let day = calendar.component(.day, from: cd)
           return day
       }
       return getCurrentDay()
   case 2:
       func getCurrentMonth() -> Int {
           let cd = Date()
           let calendar = Calendar.current
           let month = calendar.component(.month, from: cd)
           return month
       }
       return getCurrentMonth()
   default:
       print("Please choose 1 for day and 2 for month")
       return 0
   }
   
}


Call the nested function:

let dday = getDayOrMonth(choose: 1)
let dmonth = getDayOrMonth(choose: 2)
let other = getDayOrMonth(choose: 5)


For the last call, it will also print a statement as shown below:

*** End of Chapter ***

Swift 4 Book I Chapter 5: Basic Control Flow

Chapter 5: Basic Control Flow

We have two major class of control flow. The first is loops and the second is conditional branch statement.

Loops

In Swift, we have 3 types of loops, the for-in loop, while loop and repeat-while loop.

For-In Loops

As we have learned in the previous chapter, for-in loops is used to iterate a collection of data. The general syntax is as follows:

for <index_name> in <collection_of_data> {
<instruction_for_each_iteration_using_index_name>
}

Note: Please note that <index_name> is implicitly declared as a constant. <index_name> can be anything, but preferably the name is associated with the element in the array.

Example:

for numbers in 1...5 {
   
   print("Number: \(numbers)")

}



We can also perform computation as follows:

var total = 0

for index in 1...100 {
   
   total += index
}

print("Total is \(total)")


Another example:

for num in 1...8 {
   
   print("17 times \(num) is \(17 * num)")
   
}


We can also use for-in loop to perform a task a number of times.

Example:
If we want to calculate 2 to the power of 10. We can use for-in loop.

let xNumber = 2

let yPower = 10

var result = 1

for _ in 1...yPower {
   
   result *= xNumber
}

print("2 to the power of \(yPower) is \(result).")



In the previous example, we just need the loop to run yPower times. In such cases where index is not required, we can substitute the index name with underscore (_).

For-In Loop with Array


To iterate every item in an array, we use a for-in loop as follows:

var nameList = ["Peter", "Susan", "Serene", "John"]

for name in nameList {
   
   print("The name of student: \(name)")

}



To include an index, we need to use enumerated() method in array. Syntax as shown below:

for <index_name> in <collection_of_data>.enumerated() {
<instruction_for_each_iteration_using_index_name>
}


Example:
// This code is a continuation of previous code
for (indexes, name) in nameList.enumerated() {
   
    print("Student No \(20170 + indexes) is \(name)")
   
}


Additional Note:
  • We can name the indexes or name in any name. The first name will be index and the second name will be the array item.
  • We need to run the method enumerated() to include the indexes.

Listed below is an example where we flip the name and index, as shown in the result, the first name is always index regardless of what we call them.





While Loops and Repeat-While Loops

A while loop will perform a set of routine until a condition ask the loop to stop. We can use this type of loop when we do not know the number of iteration. Although we can also use it even when we know the number of iteration. In Swift, we have two type while loop, they are:
  • while loop that examine the condition first before a start of the loop.
  • repeat-while (same as do-while in other language) loop that examine the condition after the first routine is done.


While Loops

As mentioned earlier, while loop examine the condition first before running the routine. The syntax is as follows:

while <condition_that_evaluate_to_boolean_value> {
<set_of_routine_instruction>
}

Example:
We use the same example of adding 1 + 2 + … + 100. The result should be 5050.

var increment = 0

let endMark = 100

var accumulater = 0

while increment < endMark {
   
   increment += 1
   
   accumulater += increment
   
}

print("If we add 1 + 2 +...10, the result is \(accumulater).")


The previous example is not very good. A for-in loop can also do the same job with less variable. A typical example of using while loop is to display a menu and exit the loop when user ask to exit.

While userChoice != "9" {
/*
The program will continue running this routine
By displaying a menu
And accepting users' menu choice until
user choose 9 which is meant for exit
*/
}

Another example is for the loop to iterate through an array until a outlier or defect is detected. In this case, we stop the routine when we found product is less than 90% accurate:

let products = [98, 97, 99, 100, 96, 12, 98, 97]

var x = 0

while products[x] > 90 {

   print("This product is \(products[x])% accurate.")
   
   x += 1
   
}

print("Defect detected, product inspection stop now.")



The routine will stop when the accuracy is less than 90%.

Repeat-While Loop

Repeat while loop will perform a set of routine instruction first before examine the condition. The syntax is as follows:

repeat {
<set_of_routine_instruction>
} while <condition_that_evaluate_to_boolean_value>


Example:

Using the same example of adding from1 to 100.

var increment = 0

var sum = 0

let endMark = 100

repeat {
   
   sum += increment
   
   increment += 1
   
} while increment <= 100

print("The sum of adding 1 to 100 is \(sum).")


As shown in the example above, we have to run the routine 101 times since the increment and sum are 0 from the start. The first routine is not useful in this case.


Conditional Branch Statement

For most programming language, conditional branch statement consist of If-else-elseif statement and switch statement.

If Statement

We use if statement when there is only a few possible permutation. The basic syntax of if statement is as follows:

if <condition_that_evaluate_to_boolean_value> {
<set_of_routine_instruction>
}

For 2 possible permutation, the syntax is as follows:

if <condition_that_evaluate_to_boolean_value> {
<set_of_routine_instruction>
} else {
<alternative_set_of_routine_instruction>
}

For more than 2 possible permutation, the syntax is as follows:

if <condition_that_evaluate_to_boolean_value> {
<set_of_routine_instruction>
} else if <condition_that_evaluate_to_boolean_value>  {
<alternative_set_of_routine_instruction>
} else {
<alternative_set_of_routine_instruction>
}

Using if-else_if-else we can extend the permutation to many possible outcome. However, too many if statement will make the code too confusing. When there are many permutations, it is best to use switch statement.

Example:

let studentResult = 60

if studentResult >= 50 {
   
   print("This student passed.")
   
}


Example 2:

let anotherStudentResult = 47

if anotherStudentResult >= 50 {
   
   print("This student passed.")
   
} else {
   
   print("This student failed.")
   
}


Example 3:

let yetAnotherStudentResult = 63

if yetAnotherStudentResult >= 90 {
   
   print("This student grade : A")
   
} else if (yetAnotherStudentResult < 90) && (yetAnotherStudentResult >= 80) {
   
   print("This student grade : B")
   
} else if (yetAnotherStudentResult < 80) && (yetAnotherStudentResult >= 70) {
   
   print("This student grade : C")
   
} else if (yetAnotherStudentResult < 70) && (yetAnotherStudentResult >= 60) {
   
   print("This student grade : D")
   
} else if (yetAnotherStudentResult < 60) && (yetAnotherStudentResult >= 50) {
   
   print("This student grade : E")
   
} else {
   
   print("This student grade : F")
   
}



For the previous example, it is best if we use switch statement. This example just demonstrate that you can have many condition or permutation using if-elseif-else statement.

Switch Statement

Switch statement is used when we have more possible permutation in a condition evaluation. The syntax is as follows:

switch <variables> {

case <value1> :
<statement_to_execute_if_value_is_value1>
case <value2>, <value3> :
{
<group_of_statement_to_execute_if_value_is_value2_or_value3>
}
default:
<execute_the_statement_if_value_fall_outside_previous_case>
}   

Additional Note:
  • In a switch statement, every possible condition must be met.
  • The case statement must be exhaustive.
  • Each case statement must have an execution statement, otherwise error will be generated.
  • If it is not possible to list down every condition, use default as the catch all phrase.  

Example:
We convert the previous example to switch statement.

let yetAnotherStudentResult = 63

switch yetAnotherStudentResult {
case 90...100 :
   print("This student grade : A")
case 80...89 :
   print("This student grade : B")
case 70...79 :
   print("This student grade : C")
case 60...69 :
   print("This student grade : D")
case 50...59 :
   print("This student grade : E")
default:
   print("This student grade : F")
}



For multiple condition, switch is much more neater.

Compare to C and Objective-C, switch statement in Swift doesn't fall through, therefore break statement is not necessary. Switch statement in Swift will stop comparing values once the first condition is met. Switch statement in C will continue running through each condition if there is no break. Take the example below, the switch statement will act on the first case statement and stop even there is another similar condition below.

Example:

let someNumber = 98

switch someNumber {
case 90...100 :
   print("This student grade : A")
case 80...89 :
   print("This student grade : B")
//Condition same as first but it will not be executed.
case 90...100 :
   print("This student grade : C")
default:
   print("This student grade : F")
}


Each case statement must have an execution code, otherwise it will generate error.


To compare more than a value in switch, we use comma.

Example:

let someNumber2 = 67

switch someNumber2 {
case 80...100 :
   print("This student grade : A")
// In the following case we intentionally left out 69
case 70...79, 60...68 :
   print("This student grade : Pass")
case 50...59 :
   print("This student grade : Barely Pass")
default:
   print("This student grade : Fail")
}


Let's try switch statement for string.

Example:

let someLetter1 = "a"

switch someLetter1 {
case "a" :
   print("This letter is A")
default:
   print("This letter belongs to the rest of alphabet")
}

What happen if our value is A instead of a


To consider both A and a, we use comma as shown below

let someLetter2 = "A"

switch someLetter2 {
case "a", "A" :
   print("This letter is A")
default:
   print("This letter belongs to the rest of alphabet")
}


*** End of Chapter ***