C#使用Swift中的Statement等效语句

Lic*_*tia 5 c# swift

我是Swift语言的新手,我有一个C#背景.

我想知道在swift语言中是否有一个等效的C#using语句代码

using( var a = new MyClass()){
//Code Here
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*ica 5

Swift的自动引用计数保证了确定性的deinitalization(与CLR的垃圾收集器不同),因此您可以在类的deinit方法中清理代码.这与C++中的RAII完全相同.即使抛出异常,此技术仍然有效.

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.
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用延迟声明:

var a = MyClass()
defer { a.cleanUp() /* cleanup a however you wish */ }
Run Code Online (Sandbox Code Playgroud)

你失去了使用类似接口的标准化IDisposable,但你能够执行任何你想要的代码.