Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a "do statement" without catch block mean?

Tags:

swift

While reading Programming iOS 12, I came across several example codes with do statements, without catch blocks, like the following:

    do {
        let mars = UIImage(named:"Mars")!
        let sz = mars.size

        let r = UIGraphicsImageRenderer(size:CGSize(sz.width*2, sz.height), format:mars.imageRendererFormat)
        self.iv1.image = r.image { _ in
            mars.draw(at:CGPoint(0,0))
            mars.draw(at:CGPoint(sz.width,0))
        }
    }

    // ======

    do {
        let mars = UIImage(named:"Mars")!
        let sz = mars.size

        let r = UIGraphicsImageRenderer(size:CGSize(sz.width*2, sz.height*2), format:mars.imageRendererFormat)
        self.iv2.image = r.image { _ in
            mars.draw(in:CGRect(0,0,sz.width*2,sz.height*2))
            mars.draw(in:CGRect(sz.width/2.0, sz.height/2.0, sz.width, sz.height), blendMode: .multiply, alpha: 1.0)
        }
    }

I'd greatly appreciate it if someone could explain what the purpose of do statements without catch blocks is.

like image 239
gbg Avatar asked Nov 08 '18 15:11

gbg


2 Answers

It's a new scope of code: thus you can use many do statements if you want to reuse a variable name. Like in the snippet in your question, the variables mars, sz and r exist in both scopes without errors.

A do statement may be labeled, which gives you the ability to get out of that scope:

scopeLabel: do {
    for i in 0..<10 {
        for j in 0..<20 {
            if i == 2, j == 15 {
                break scopeLabel
            }
            else {
                print(i,j)
            }
        }
    }
}

For more details, have a look here.

like image 170
ielyamani Avatar answered Oct 29 '22 14:10

ielyamani


Since here there is nothing that would through an error , then using do so code writer can copy paste same content without changing var names as var scope is the do block

I don't support this way he would create a function to avoid repeating code so it will has it's scope

like image 41
Sh_Khan Avatar answered Oct 29 '22 12:10

Sh_Khan