This is my test code (run in the terminal):
#!/usr/bin/xcrun swift
var count = 0; // for reference counting
class A {
init() {
count++;
}
deinit {
println("A deinit")
count--;
}
}
var a: A? = A()
println(count)
a = nil // no output if I comment out this statement
println(count)
Output:
1
A deinit
0
There is no output "A deinit" if the line mentioned above is commented out. And the output will be:
1
1
I've used swiftc
to compile the code but the result is still the same. (xcrun swiftc -o test test.swift
)
Is it by design that the stdout will be closed when the program exits, or the objects are still referred (by what?) when they are destructed?
Update: Thanks to @Logan , now I have more details about it.
When it is run inside a function, it will output A deinit
even if I comment out a = nil
:
#!/usr/bin/xcrun swift
class A {
deinit {
println("A deinit")
}
}
func test() {
var a: A? = A()
//a = nil
}
test()
I'm not using a playground in Xcode. :-$
Update
#!/usr/bin/xcrun swift
import Foundation
class A {
deinit {
var s = "A deinit"
println(s)
var a: A? = A()
a = nil
var error: NSError?
var path = "\(NSFileManager.defaultManager().currentDirectoryPath)/swift_test.txt"
if s.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: &error) {
println("File saved at \(path)")
} else {
println(error)
}
}
}
//func test() {
var a: A? = A()
//}
//test()
Result: No output to stdout or the file, unless running in the test
function.