11

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
gbg
  • 123
  • 8
  • Related: [How to create local scopes in Swift?](https://stackoverflow.com/questions/24011271/how-to-create-local-scopes-in-swift) and [Does swift allow code blocks without conditions/loops to reduce local variable scope?](https://stackoverflow.com/questions/39109651/does-swift-allow-code-blocks-without-conditions-loops-to-reduce-local-variable-s) – Martin R Nov 08 '18 at 15:13

2 Answers2

11

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.

ielyamani
  • 17,807
  • 10
  • 55
  • 90
5

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

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87