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
}
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.
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#)
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