Consider the following example class:
class SocketWrapper {
let sock: Int32
init() throws {
try sock = SocketWrapper.createSocket()
}
deinit {
close(sock)
}
}
What happens if createSocket() throws and the init() therefore fails? sock would be left uninitialized. Is deinit still called (on an partially uninitialized object) when init() throws?
deinit is not called on instances that have not been correctly initialized.
If init fails for some reason, then the class instance never starts existing. Therefore, there is no instance on which deinit could be called.
If deinit could be called on a partially initialized instance, it would break the contract of non-optional properties - in your example the socket property would not get assigned and it would still be accessible in deinit as a non-optional but without a value.
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