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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With