Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# using Statement equivalent in Swift

Tags:

c#

swift

I'm very new to Swift language, I have a C# Background.

and I'm wondering if there is an equivalent code for C# using statement in swift Language

using( var a = new MyClass()){
//Code Here
}
like image 875
Asım Gündüz Avatar asked Dec 30 '16 09:12

Asım Gündüz


2 Answers

Swift's automatic reference counting guarantees deterministic deinitalization (unlike the CLR's garbage collector), so you can put clean up code in your class' deinit method. This is exactly like RAII in C++. This technique 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 a defer statement:

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

You lose the standardization of using an Interface like IDisposable, but you gain generality in being able to execute whatever code you wish.

like image 167
Alexander Avatar answered Sep 28 '22 06:09

Alexander


Just learning Swift and came up with the same question.

The closest I could get was this:

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


   }

It's a bit of a hack on optional binding but seems to work. You will need to make sure your class has a deinit defined as called out above by Alexander. I found that even if my init throws an exception, the deinit method is still called as soon as you go out of scope on the IF statement.

NOTE: Make sure you are using weak references if applicable to make sure your deinit actually gets called!

It is probably more Swifty to use a DO block for your scoping:

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

Which has the benefit of avoiding a "pyramid of doom" with your pseudo using blocks (like you'll get in c#)

like image 26
Tom K Avatar answered Sep 28 '22 07:09

Tom K