C # using equivalent statement in Swift

I am very new to Swift, I have C # background.

and I am wondering if there is equivalent code for C # using the instruction in swift Language

using( var a = new MyClass()){ //Code Here } 
+5
source share
2 answers

A quick reference counter guarantees deterministic de-initialization (unlike the CLR garbage collector), so you can put the cleanup code in your deinit class. This is similar to RAII in C ++. This method works even if an exception is thrown.

 class MyClass() { var db = openDBConnection() //example resource deinit() { db.close() } } func foo() { var a = MyClass() print(a) // do stuff with a // the (only) reference, a, will go out of scope, // thus the instance will be deinitialized. } 

You can also use the defer statement:

 var a = MyClass() defer { a.cleanUp() /* cleanup a however you wish */ } 

You lose the standardization of using an interface such as IDisposable , but you get a commonality in being able to execute whatever code you want.

+5
source

Just by studying Swift and came up with the same question.

The closest I could get was the following:

  if let UOW = (try UnitOfWork() as UnitOfWork?) { } 

This is a little hack to optional binding, but seems to work. You will need to make sure your class has the deinit specified above, named above by Alexander. I found that even if my init throws an exception, the deinit method is still called as soon as you exit the scope in the IF statement.

NOTE. Make sure you use weak links, if applicable, to make sure your deinit is really caused!

Most likely, more Swifty uses the DO block for your review:

 do { let UOW = try UnitOfWork() // your code here } 

What is the advantage of avoiding the death pyramid with your pseudo-blocks (for example, you will get C #)

+1
source

Source: https://habr.com/ru/post/1262068/


All Articles