Swift Deinitialization
A deinitializer is called automatically just before a class instance is deallocated, to perform resource cleanup.
It's declared with the deinit keyword; only class types have deinitializers—structs and enums don't.
deinit syntax and timing of execution
Each class can have at most one deinitializer; it takes no parameters and is written without parentheses.
deinit {
// Perform cleanup
}
The deinitializer is called automatically by the system when the instance is about to be deallocated; you neither need nor can call it yourself.
The example below uses a static counter to observe instance creation and destruction.
Example
import Foundation
class
RunoobCounter
{
static
var count
=
0
init
(
)
{
RunoobCounter.
count
=
1
(
"Instance created, current count: (RunoobCounter.count)"
)
}
deinit
{
RunoobCounter.
count
=
1
(
"Instance deallocated, current count: (RunoobCounter.count)"
)
}
}
var a
:
RunoobCounter
?
=
RunoobCounter
(
)
var b
:
RunoobCounter
?
=
RunoobCounter
(
)
a
=
nil
b
=
nil
Running result:
创建实例,当前实例数:1
创建实例,当前实例数:2
释放实例,当前实例数:1
释放实例,当前实例数:0
After assigning nil to an optional variable, the instance it held loses its reference and the deinitializer is called immediately.
A more common trigger is the end of a scope: a local variable is destroyed when the function returns, so the deinitializer runs naturally.
Example
import Foundation
class
FileHandler
{
let path
:
String
init
(
path
:
String
)
{
self.
path
=
path
(
"Open file: (path)"
)
}
deinit
{
// Before the instance is deallocated, close the resources it holds
(
"Close file: (path)"
)
}
}
func useFile
(
)
{
let handler
=
FileHandler
(
path
:
"www.runoob.com/data.txt"
)
(
"Using (handler.path)"
)
// When the function ends, handler goes out of scope, the reference count drops to zero, and deinit is called
}
useFile
(
)
(
"useFile has returned"
)
Running result:
打开文件:www.runoob.com/data.txt
正在使用 www.runoob.com/data.txt
关闭文件:www.runoob.com/data.txt
useFile 已返回
Note the output order: "Close file" appears before "useFile has returned," showing that deinitialization happens at the moment the function returns.
Can't be called manually or throw errors
The deinitializer is called automatically by the runtime; writing instance.deinit or similar calls in code isn't allowed.
A deinitializer also can't be declared throws or throw errors, because it runs during instance destruction with no suitable caller to receive an error.
| Limitation | Description |
|---|---|
| Count | At most one deinitializer per class |
| Parameters | No parameters and no parentheses |
| How to call | Called only automatically by the system, never manually |
| Error handling | Can't throw errors or be declared throws |
| Applicable to types | Only classes have deinitializers |
Note:A subclass deinitializer automatically calls the superclass deinitializer after its own cleanup finishes; you don't and can't write this explicitly
super.deinit()。
Working with ARC
Swift manages instance memory with Automatic Reference Counting (ARC), and the timing of deinitialization is determined by the reference count.
As long as one strong reference points to the instance, it won't be deallocated; only when the last strong reference disappears and the count reaches zero does the deinitializer run.
Example
import Foundation
class
Resource
{
let name
:
String
init
(
name
:
String
)
{
self.
name
=
name
(
"Initialize (name)"
)
}
deinit
{
(
"Deinitialize (name)"
)
}
}
var strongRef
:
Resource
?
=
Resource
(
name
:
"Runoob"
)
var anotherRef
=
strongRef
// A second strong reference raises the count to 2
strongRef
=
nil
// Reference count drops by one, but the object is still alive
(
"After strongRef is set to nil, anotherRef is still usable: (anotherRef!.name)"
)
anotherRef
=
nil
// Only when the last strong reference disappears does deinit run
(
"Program ends"
)
Running result:
初始化 Runoob
strongRef 置为 nil 后,anotherRef 仍然可用:Runoob
析构 Runoob
程序结束
If two objects hold strong references to each other, a reference cycle forms, the count never reaches zero, and the deinitializer never runs.
Example
import Foundation
class
Node
{
let name
:
String
var next
:
Node
?
init
(
name
:
String
)
{
self.
name
=
name
}
deinit
{
(
"Deinitialize (name)"
)
}
}
var first
:
Node
?
=
Node
(
name
:
"A"
)
var second
:
Node
?
=
Node
(
name
:
"B"
)
first
?
.
next
=
second
second
?
.
next
=
first
// Mutual strong references form a reference cycle
first
=
nil
second
=
nil
(
"After setting to nil there's no deinit output, showing neither object was deallocated"
)
Running result:
置为 nil 后没有任何析构信息,说明两个对象都没有被释放
The fix is to change one of the references to weak or unowned; see 《 for moreSwift Automatic Reference Counting》。
Common questions
The deinitializer's syntax is simple; problems usually arise from misunderstanding when deallocation happens.
deinit is never called
The most common cause is a strong reference cycle, or a global variable or closure holding the instance long-term. Check your object graph for mutual strong references.
Can you access other properties in deinit
You can read the instance's own properties, but since it's about to be destroyed, you shouldn't pass itself or its properties out to be held long-term by others, or you'll cause hard-to-diagnose issues.
Why don't structs have deinit
Deinitializers are for classes only. Value types are destroyed directly by the compiler at scope end, with no hook for custom cleanup; wrap them in a class when you need to clean up resources.