Search Your Question

Different types of Control statements.

Ans. 

Control flow statements are used to control the flow of execution in a program.

1. Loop Statement : 

For-in

let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    print("Hello, \(name)!")

}


While 
var i:Int = 0
while i < 10 {
    print(i)
    i += 1
}

repeat-while
var j: Int = 10
repeat {
   print(j)
}
while(j < 10)

2. Branch Statement : 

If-else
var numArray = [10, 20, 30, 40, 50, 60, 70]
if(numArray.contains(20)){
    print("true it contains 20")
}else{
    print("number is not there")
}

guard
guard condition else {
    statements
}

The else clause of a guard statement is required, and must either call a function with the Never return type or transfer program control outside the guard statement’s enclosing scope using one of the following statements:  
  • return 
  • break 
  • continue
  •  throw
Switch
switch grade {
    
case 90 ..< 100:
    print("A")
case (80 ..< 90):
    print("B")
case (70 ..< 80):
    print("C")
case (0 ..< 70):
    print("D")
    
default:
    print("F. You failed")//Any number less than 0 or greater than 99
    
}

3. Control Transfer Statement : 
continue 
let numbersArray = [20, 30, 40, 50, 60, 70, 80, 90, 10]
for num in numbersArray{
    if(num > 10){
        continue
    }
    print(num)
}

// prints: 10

break 
let numbersArray = [20, 30, 40, 50, 60, 70, 80, 90, 10]
for num in numbersArray{
    if num > 30{
        break
    }
    print(num)
}


fallthrough : switch statements don’t fallthrough the bottom of each case and into the next one. That is, the entire switch statement completes its execution as soon as the first matching case is completed.

for num in numbersArray{
    switch num {
    case 10:
        print(num)
    case 20:
        print(num)
    case 30:
        print(num)
        fallthrough
    case 40:
        print(num)
    default:
        print("nothing here")
    }
}

return :
func myFunc() -> Int {
    let myNumber = 16 % 3
    if myNumber == 0 {
        return 0
    }
    else if myNumber == 1 {
        return 1
    }
    return 0
}

throw
enum ErrorsToThrow: Error {
    case fileNotFound
    case fileNotReadable
    case fileSizeIsTooHigh
}
class documents {
    
    init() {
        do {
            let dataFromString = try? readFiles(path: "")
            print(dataFromString)
        } catch ErrorsToThrow.fileNotFound {
            print("error generated1")
        } catch ErrorsToThrow.fileNotReadable {
            print("error generated2")
        } catch ErrorsToThrow.fileSizeIsTooHigh {
            print("error generated3")
        } catch {
                print("error")
        }
    }
    
func readFiles(path:String) throws  ->String {
        if path == "" {
            throw ErrorsToThrow.fileNotFound
        }
        return "Data from file"

    }
}



No comments:

Post a Comment

Thanks