Control Transfer Statements in iOS Programming Language Tutorial | What is the difference between continue, break, fall-through, throw and return in Swift Programming?

 

ios programming language tutorial,advanced swift,case statement syntax,,coding ios,,control swift,for loop swift example,,if conditional programming,




Control transfer statements change the order during which your code is executed, by transferring control from one piece of code to a different 

Swift has five control transfer statements. What are they, and how can they be used?

  • continue
  • break
  • fallthrough
  • return
  • throw

Continue:

The continue statement tells a loop to stop what it is doing and start again at the beginning of the next iteration through the loop. 

        var sum = 0
        for n in 0..<5 {

            if (n == 4) {
                continue
            }
            print("count loop value", n)
                sum += n
            print("Sum value", sum)
        }


// Output
count loop value 0
Sum value 0
count loop value 1
Sum value 1
count loop value 2
Sum value 3
count loop value 3
Sum value 6

Break:

A break statement ends program execution of a loop, an if statement, or a switch statement.

var sum = 0
        for n in 0..<5 {

            if (n == 4) {
                break
            }
            print("count loop value", n)
                sum += n
            print("Sum value", sum)
        }


// Output
count loop value 0
Sum value 0
count loop value 1
Sum value 1
count loop value 2
Sum value 3
count loop value 3
Sum value 6

Fallthrough:

Fallthrough is a keyword used in switch statement.If fallthrough exits in a sucessfull case it execute the next case irrespective of the case value match.

var sum = 0
    let num = 6
    switch num {
    case 2:
        sum += num
        print(sum)
    case 4:
        sum += num
          print(sum)
    case 6:
        sum += num
          print(sum)
        fallthrough
    default:
        sum += 10
        print(sum)
            }

//Output
6
16

Throw:

  • Use a throw statement to handle the error 
  • throw statement is used to stop current execution of functions or methods and throw error messages based on our requirements.

        
     enum DividingErr : ErrorType {

     case InvalidNumber

}

func divby(value: Int) throws -> Int {

guard value != 0 else {

throw DividingErr.InvalidNumber

}

return 20 
}

let res = try! divby(3)

print(res) //6

Return:

A return statement occurs in the body of a function or method definition and causes program execution to return to the calling function or method.

 
      override func viewDidLoad() {
            super.viewDidLoad()
        
           print(returnFunc(name: "AppCodeZip"))
         }
  
        func returnFunc(name: String) -> String{
        return name
    }

//Output
AppCodeZip

HAPPY LEARNING! 


Similar iOS Programming tutorial you may also like...

Post a Comment

0 Comments