Question: C# using Statement equivalent in Swift


C# using Statement equivalent in Swift

Answers 1
Added at 2016-12-30 10:12

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
Answers to

C# using Statement equivalent in Swift

nr: #1 dodano: 2016-12-30 10:12

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() {

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.

Source Show
◀ Wstecz