Automatic Reference Counting (自动引用计数)

2017.01.20 10:11* 字数 11575

Swift usesAutomatic Reference Counting(ARC) to track and manage your app’s memory usage. In most cases, this means that memory management “just works” in Swift, and you do not need to think about memory management yourself. ARC automatically frees up the memory used by class instances when those instances are no longer needed.

Swift 使用自动引用计数(ARC)机制来跟踪和管理你的应用程序的内存。通常情况下,Swift 内存管理机制会一直起作用,你无须自己来考虑内存的管理。ARC 会在类的实例不再被使用时,自动释放其占用的内存。

However, in a few cases ARC requires more information about the relationships between parts of your code in order to manage memory for you. This chapter describes those situations and shows how you enable ARC to manage all of your app’s memory. Using ARC in Swift is very similar to the approach described inTransitioning to ARC Release Notesfor using ARC with Objective-C.

然而在少数情况下,为了能帮助你管理内存,ARC 需要更多的,代码之间关系的信息。本章描述了这些情况,并且为你示范怎样才能使 ARC 来管理你的应用程序的所有内存。在 Swift 使用 ARC 与在 Obejctive-C 中使用 ARC 非常类似,具体请参考过渡到 ARC 的发布说明


Reference counting only applies to instances of classes. Structures and enumerations are value types, not reference types, and are not stored and passed by reference.


How ARC Works (自动引用计数的工作机制)

Every time you create a new instance of a class, ARC allocates a chunk of memory to store information about that instance. This memory holds information about the type of the instance, together with the values of any stored properties associated with that instance.

当你每次创建一个类的新的实例的时候,ARC 会分配一块内存来储存该实例信息。内存中会包含实例的类型信息,以及这个实例所有相关的存储型属性的值。

Additionally, when an instance is no longer needed, ARC frees up the memory used by that instance so that the memory can be used for other purposes instead. This ensures that class instances do not take up space in memory when they are no longer needed.

此外,当实例不再被使用时,ARC 释放实例所占用的内存,并让释放的内存能挪作他用。这确保了不再被使用的实例,不会一直占用内存空间。

However, if ARC were to deallocate an instance that was still in use, it would no longer be possible to access that instance’s properties, or call that instance’s methods. Indeed, if you tried to access the instance, your app would most likely crash.

然而,当 ARC 收回和释放了正在被使用中的实例,该实例的属性和方法将不能再被访问和调用。实际上,如果你试图访问这个实例,你的应用程序很可能会崩溃。

To make sure that instances don’t disappear while they are still needed, ARC tracks how many properties, constants, and variables are currently referring to each class instance. ARC will not deallocate an instance as long as at least one active reference to that instance still exists.

为了确保使用中的实例不会被销毁,ARC 会跟踪和计算每一个实例正在被多少属性,常量和变量所引用。哪怕实例的引用数为1,ARC都不会销毁这个实例。

To make this possible, whenever you assign a class instance to a property, constant, or variable, that property, constant, or variable makes astrong referenceto the instance. The reference is called a “strong” reference because it keeps a firm hold on that instance, and does not allow it to be deallocated for as long as that strong reference remains.


ARC in Action (自动引用计数实践)

Here’s an example of how Automatic Reference Counting works. This example starts with a simple class calledPerson, which defines a stored constant property calledname:


class Person{

    let name:String

    init (name:String) {


        print("\(name)is being initialized")


    deinit {

        print("\(name)is being deinitialized") 



ThePersonclass has an initializer that sets the instance’snameproperty and prints a message to indicate that initialization is underway. ThePersonclass also has a deinitializer that prints a message when an instance of the class is deallocated.


The next code snippet defines three variables of typePerson?, which are used to set up multiple references to a newPersoninstance in subsequent code snippets. Because these variables are of an optional type (Person?, notPerson), they are automatically initialized with a value ofnil, and do not currently reference aPersoninstance.


var reference1:Person?

var reference2:Person?

var reference3:Person?

You can now create a new Person instance and assign it to one of these three variables:


reference1 = Person(name:"John Appleseed")

// Prints "John Appleseed is being initialized"

Note that the message"John Appleseed is being initialized"is printed at the point that you call thePersonclass’s initializer. This confirms that initialization has taken place.

应当注意到当你调用Person类的构造函数的时候,“John Appleseed is being initialized”会被打印出来。由此可以确定构造函数被执行。

Because the newPersoninstance has been assigned to thereference1variable, there is now a strong reference fromreference1to the newPersoninstance. Because there is at least one strong reference, ARC makes sure that thisPersonis kept in memory and is not deallocated.

由于Person类的新实例被赋值给了reference1变量,所以reference1到Person类的新实例之间建立了一个强引用。正是因为这一个强引用,ARC 会保证Person实例被保持在内存中不被销毁。

If you assign the samePersoninstance to two more variables, two more strong references to that instance are established:


reference2 = reference1

reference3 = reference1

There are nowthreestrong references to this singlePersoninstance.


If you break two of these strong references (including the original reference) by assigningnilto two of the variables, a single strong reference remains, and thePersoninstance is not deallocated:


reference1 = nil

reference2 = nil

ARC does not deallocate thePersoninstance until the third and final strong reference is broken, at which point it is clear that you are no longer using thePersoninstance:

在你清楚地表明不再使用这个Person实例时,即第三个也就是最后一个强引用被断开时,ARC 会销毁它:


// Prints "John Appleseed is being deinitialized"

Strong Reference Cycles Between Class Instances (类实例之间的循环强引用)

In the examples above, ARC is able to track the number of references to the newPersoninstance you create and to deallocate thatPersoninstance when it is no longer needed.

在上面的例子中,ARC 会跟踪你所新创建的Person实例的引用数量,并且会在Person实例不再被需要时销毁它。

However, it is possible to write code in which an instance of a classnevergets to a point where it has zero strong references. This can happen if two class instances hold a strong reference to each other, such that each instance keeps the other alive. This is known as astrong reference cycle.


You resolve strong reference cycles by defining some of the relationships between classes as weak or unowned references instead of as strong references. This process is described inResolving Strong Reference Cycles Between Class Instances. However, before you learn how to resolve a strong reference cycle, it is useful to understand how such a cycle is caused.


Here’s an example of how a strong reference cycle can be created by accident. This example defines two classes calledPersonandApartment, which model a block of apartments and its residents:


class Person{

    let name:String

    init(name:String) {self.name=name}

    var apartment:Apartment?

    deinit {print("\(name)is being deinitialized") }


class Apartment{

let unit:String

init(unit:String) {self.unit=unit}

var tenant:Person?

deinit {print("Apartment\(unit)is being deinitialized") }


EveryPersoninstance has anameproperty of typeStringand an optionalapartmentproperty that is initiallynil. Theapartmentproperty is optional, because a person may not always have an apartment.


Similarly, everyApartmentinstance has aunitproperty of typeStringand has an optionaltenantproperty that is initiallynil. The tenant property is optional because an apartment may not always have a tenant.


Both of these classes also define a deinitializer, which prints the fact that an instance of that class is being deinitialized. This enables you to see whether instances ofPersonandApartmentare being deallocated as expected.


This next code snippet defines two variables of optional type calledjohnandunit4A, which will be set to a specificApartmentandPersoninstance below. Both of these variables have an initial value ofnil, by virtue of being optional:


var john:Person?

var unit4A:Apartment?

You can now create a specificPersoninstance andApartmentinstance and assign these new instances to thejohnandunit4Avariables:


john = Person(name:"John Appleseed")

unit4A = Apartment(unit:"4A")

Here’s how the strong references look after creating and assigning these two instances. Thejohnvariable now has a strong reference to the newPersoninstance, and theunit4Avariable has a strong reference to the newApartmentinstance:


You can now link the two instances together so that the person has an apartment, and the apartment has a tenant. Note that an exclamation mark (!) is used to unwrap and access the instances stored inside thejohnandunit4Aoptional variables, so that the properties of those instances can be set:




Here’s how the strong references look after you link the two instances together:


Unfortunately, linking these two instances creates a strong reference cycle between them. ThePersoninstance now has a strong reference to theApartmentinstance, and theApartmentinstance has a strong reference to thePersoninstance. Therefore, when you break the strong references held by thejohnandunit4Avariables, the reference counts do not drop to zero, and the instances are not deallocated by ARC:

不幸的是,这两个实例关联后会产生一个循环强引用。Person实例现在有了一个指向Apartment实例的强引用,而Apartment实例也有了一个指向Person实例的强引用。因此,当你断开john和unit4A变量所持有的强引用时,引用计数并不会降为0,实例也不会被 ARC 销毁:



Note that neither deinitializer was called when you set these two variables tonil. The strong reference cycle prevents thePersonandApartmentinstances from ever being deallocated, causing a memory leak in your app.


Here’s how the strong references look after you set thejohnandunit4Avariables tonil:


The strong references between thePersoninstance and theApartmentinstance remain and cannot be broken.


Resolving Strong Reference Cycles Between Class Instances (解决实例之间的循环强引用)

Swift provides two ways to resolve strong reference cycles when you work with properties of class type: weak references and unowned references.

Swift 提供了两种办法用来解决你在使用类的属性时所遇到的循环强引用问题:弱引用(weak reference)和无主引用(unowned reference)。

Weak and unowned references enable one instance in a reference cycle to refer to the other instancewithoutkeeping a strong hold on it. The instances can then refer to each other without creating a strong reference cycle.


Use a weak reference when the other instance has a shorter lifetime—that is, when the other instance can be deallocated first. In theApartmentexample above, it is appropriate for an apartment to be able to have no tenant at some point in its lifetime, and so a weak reference is an appropriate way to break the reference cycle in this case. In contrast, use an unowned reference when the other instance has the same lifetime or a longer lifetime.


Weak References (弱引用)

Aweak referenceis a reference that does not keep a strong hold on the instance it refers to, and so does not stop ARC from disposing of the referenced instance. This behavior prevents the reference from becoming part of a strong reference cycle. You indicate a weak reference by placing theweakkeyword before a property or variable declaration.

弱引用不会对其引用的实例保持强引用,因而不会阻止 ARC 销毁被引用的实例。这个特性阻止了引用变为循环强引用。声明属性或者变量时,在前面加上weak关键字表明这是一个弱引用。

Because a weak reference does not keep a strong hold on the instance it refers to, it is possible for that instance to be deallocated while the weak reference is still referring to it. Therefore, ARC automatically sets a weak reference tonilwhen the instance that it refers to is deallocated. And, because weak references need to allow their value to be changed tonilat runtime, they are always declared as variables, rather than constants, of an optional type.

因为弱引用不会保持所引用的实例,即使引用存在,实例也有可能被销毁。因此,ARC 会在引用的实例被销毁后自动将其赋值为nil。并且因为弱引用可以允许它们的值在运行时被赋值为nil,所以它们会被定义为可选类型变量,而不是常量。

You can check for the existence of a value in the weak reference, just like any other optional value, and you will never end up with a reference to an invalid instance that no longer exists.



Property observers aren’t called when ARC sets a weak reference tonil.

当 ARC 设置弱引用为nil时,属性观察不会被触发。

The example below is identical to thePersonandApartmentexample from above, with one important difference. This time around, theApartmenttype’stenantproperty is declared as a weak reference:


class Person{

    let name:String

    init(name:String) {self.name=name}

    var apartment:Apartment?

    deinit {print("\(name)is being deinitialized") }


class Apartment{

    let unit:String

    init(unit:String) {self.unit=unit}

    weak var tenant:Person?

    deinit{print("Apartment\(unit)is being deinitialized") }


The strong references from the two variables (johnandunit4A) and the links between the two instances are created as before:


var john:Person?

var unit4A:Apartment?

john=Person(name:"John Appleseed")




Here’s how the references look now that you’ve linked the two instances together:


ThePersoninstance still has a strong reference to theApartmentinstance, but theApartmentinstance now has aweakreference to thePersoninstance. This means that when you break the strong reference held by thejohnvariable by setting it tonil, there are no more strong references to thePersoninstance:


john = nil

// Prints "John Appleseed is being deinitialized"

Because there are no more strong references to thePersoninstance, it is deallocated and thetenantproperty is set tonil:


The only remaining strong reference to theApartmentinstance is from theunit4Avariable. If you breakthatstrong reference, there are no more strong references to theApartmentinstance:



// Prints "Apartment 4A is being deinitialized"

Because there are no more strong references to theApartmentinstance, it too is deallocated:



In systems that use garbage collection, weak pointers are sometimes used to implement a simple caching mechanism because objects with no strong references are deallocated only when memory pressure triggers garbage collection. However, with ARC, values are deallocated as soon as their last strong reference is removed, making weak references unsuitable for such a purpose.

在使用垃圾收集的系统里,弱指针有时用来实现简单的缓冲机制,因为没有强引用的对象只会在内存压力触发垃圾收集时才被销毁。但是在 ARC 中,一旦值的最后一个强引用被移除,就会被立即销毁,这导致弱引用并不适合上面的用途。

Unowned References (无主引用)

Like a weak reference, anunowned referencedoes not keep a strong hold on the instance it refers to. Unlike a weak reference, however, an unowned reference is used when the other instance has the same lifetime or a longer lifetime. You indicate an unowned reference by placing theunownedkeyword before a property or variable declaration.


An unowned reference is expected to always have a value. As a result, ARC never sets an unowned reference’s value tonil, which means that unowned references are defined using nonoptional types.

无主引用通常都被期望拥有值。不过 ARC 无法在实例被销毁后将无主引用设为nil,因为非可选类型的变量不允许被赋值为nil。


Use an unowned reference only when you are sure that the referencealwaysrefers to an instance that has not been deallocated.


If you try to access the value of an unowned reference after that instance has been deallocated, you’ll get a runtime error.


The following example defines two classes,CustomerandCreditCard, which model a bank customer and a possible credit card for that customer. These two classes each store an instance of the other class as a property. This relationship has the potential to create a strong reference cycle.


The relationship betweenCustomerandCreditCardis slightly different from the relationship betweenApartmentandPersonseen in the weak reference example above. In this data model, a customer may or may not have a credit card, but a credit card willalwaysbe associated with a customer. ACreditCardinstance never outlives theCustomerthat it refers to. To represent this, theCustomerclass has an optionalcardproperty, but theCreditCardclass has an unowned (and nonoptional)customerproperty.


Furthermore, a newCreditCardinstance canonlybe created by passing anumbervalue and acustomerinstance to a customCreditCardinitializer. This ensures that aCreditCardinstance always has acustomerinstance associated with it when theCreditCardinstance is created.


Because a credit card will always have a customer, you define itscustomerproperty as an unowned reference, to avoid a strong reference cycle:


class Customer{

    let name:String

    var card:CreditCard?

    init(name:String) {



deinit{print("\(name)is being deinitialized") }


class CreditCard{

    let number:UInt64 

    unowned let customer:Customer

    init(number:UInt64,customer:Customer) {




deinit{print("Card #\(number)is being deinitialized") }



Thenumberproperty of theCreditCardclass is defined with a type ofUInt64rather thanInt, to ensure that thenumberproperty’s capacity is large enough to store a 16-digit card number on both 32-bit and 64-bit systems.

CreditCard类的number属性被定义为UInt64类型而不是Int类型,以确保number属性的存储量在 32 位和 64 位系统上都能足够容纳 16 位的卡号。

This next code snippet defines an optionalCustomervariable calledjohn, which will be used to store a reference to a specific customer. This variable has an initial value of nil, by virtue of being optional:


var john:Customer?

You can now create aCustomerinstance, and use it to initialize and assign a newCreditCardinstance as that customer’scardproperty:


john=Customer(name:"John Appleseed")


Here’s how the references look, now that you’ve linked the two instances:


TheCustomerinstance now has a strong reference to theCreditCardinstance, and theCreditCardinstance has an unowned reference to theCustomerinstance.


Because of the unownedcustomerreference, when you break the strong reference held by thejohnvariable, there are no more strong references to theCustomerinstance:


Because there are no more strong references to theCustomerinstance, it is deallocated. After this happens, there are no more strong references to theCreditCardinstance, and it too is deallocated:



// Prints "John Appleseed is being deinitialized"

// Prints "Card #1234567890123456 is being deinitialized"

The final code snippet above shows that the deinitializers for theCustomerinstance andCreditCardinstance both print their “deinitialized” messages after thejohnvariable is set tonil.



The examples above show how to usesafeunowned references. Swift also providesunsafeunowned references for cases where you need to disable runtime safety checks—for example, for performance reasons. As with all unsafe operations, you take on the responsiblity for checking that code for safety.


You indicate an unsafe unowned reference by writingunowned(unsafe). If you try to access an unsafe unowned reference after the instance that it refers to is deallocated, your program will try to access the memory location where the instance used to be, which is an unsafe operation.


Unowned References and Implicitly Unwrapped Optional Properties (无主引用以及隐式解析可选属性)

The examples for weak and unowned references above cover two of the more common scenarios in which it is necessary to break a strong reference cycle.


ThePersonandApartmentexample shows a situation where two properties, both of which are allowed to benil, have the potential to cause a strong reference cycle. This scenario is best resolved with a weak reference.


TheCustomerandCreditCardexample shows a situation where one property that is allowed to beniland another property that cannot benilhave the potential to cause a strong reference cycle. This scenario is best resolved with an unowned reference.


However, there is a third scenario, in whichbothproperties should always have a value, and neither property should ever benilonce initialization is complete. In this scenario, it is useful to combine an unowned property on one class with an implicitly unwrapped optional property on the other class.


This enables both properties to be accessed directly (without optional unwrapping) once initialization is complete, while still avoiding a reference cycle. This section shows you how to set up such a relationship.


The example below defines two classes,CountryandCity, each of which stores an instance of the other class as a property. In this data model, every country must always have a capital city, and every city must always belong to a country. To represent this, theCountryclass has acapitalCityproperty, and theCityclass has acountryproperty:


class Country{

    let name:String

    var capitalCity:City!

    init(name:String,capitalName:String) {





class City{

    let name:String

    unowned let country:Country

    init(name:String,country:Country) {





To set up the interdependency between the two classes, the initializer forCitytakes aCountryinstance, and stores this instance in itscountryproperty.


The initializer forCityis called from within the initializer forCountry. However, the initializer forCountrycannot passselfto theCityinitializer until a newCountryinstance is fully initialized, as described inTwo-Phase Initialization.


To cope with this requirement, you declare thecapitalCityproperty ofCountryas an implicitly unwrapped optional property, indicated by the exclamation mark at the end of its type annotation (City!). This means that thecapitalCityproperty has a default value ofnil, like any other optional, but can be accessed without the need to unwrap its value as described inImplicitly Unwrapped Optionals.


BecausecapitalCityhas a defaultnilvalue, a newCountryinstance is considered fully initialized as soon as theCountryinstance sets itsnameproperty within its initializer. This means that theCountryinitializer can start to reference and pass around the implicitselfproperty as soon as thenameproperty is set. TheCountryinitializer can therefore passselfas one of the parameters for theCityinitializer when theCountryinitializer is setting its owncapitalCityproperty.


All of this means that you can create theCountryandCityinstances in a single statement, without creating a strong reference cycle, and thecapitalCityproperty can be accessed directly, without needing to use an exclamation mark to unwrap its optional value:


var country=Country(name:"Canada",capitalName:"Ottawa")

print("\(country.name)'s capital city is called\(country.capitalCity.name)")

// Prints "Canada's capital city is called Ottawa"

In the example above, the use of an implicitly unwrapped optional means that all of the two-phase class initializer requirements are satisfied. ThecapitalCityproperty can be used and accessed like a nonoptional value once initialization is complete, while still avoiding a strong reference cycle.


Strong Reference Cycles for Closures (闭包引起的循环强引用)

You saw above how a strong reference cycle can be created when two class instance properties hold a strong reference to each other. You also saw how to use weak and unowned references to break these strong reference cycles.


A strong reference cycle can also occur if you assign a closure to a property of a class instance, and the body of that closure captures the instance. This capture might occur because the closure’s body accesses a property of the instance, such asself.someProperty, or because the closure calls a method on the instance, such asself.someMethod(). In either case, these accesses cause the closure to “capture”self, creating a strong reference cycle.


This strong reference cycle occurs because closures, like classes, arereference types. When you assign a closure to a property, you are assigning areferenceto that closure. In essence, it’s the same problem as above—two strong references are keeping each other alive. However, rather than two class instances, this time it’s a class instance and a closure that are keeping each other alive.


Swift provides an elegant solution to this problem, known as aclosure capture list. However, before you learn how to break a strong reference cycle with a closure capture list, it is useful to understand how such a cycle can be caused.

Swift 提供了一种优雅的方法来解决这个问题,称之为闭包捕获列表(closure capture list)。同样的,在学习如何用闭包捕获列表打破循环强引用之前,先来了解一下这里的循环强引用是如何产生的,这对我们很有帮助。

The example below shows how you can create a strong reference cycle when using a closure that referencesself. This example defines a class calledHTMLElement, which provides a simple model for an individual element within an HTML document:

下面的例子为你展示了当一个闭包引用了self后是如何产生一个循环强引用的。例子中定义了一个叫HTMLElement的类,用一种简单的模型表示 HTML 文档中的一个单独的元素:

class HTMLElement{

    let name:String

    let text:String?

    lazy var asHTML: () ->String= {

    if let text=self.text{


    } else {




init(name:String,text:String? =nil) {





print("\(name)is being deinitialized")



TheHTMLElementclass defines anameproperty, which indicates the name of the element, such as"h1"for a heading element,"p"for a paragraph element, or"br"for a line break element.HTMLElementalso defines an optionaltextproperty, which you can set to a string that represents the text to be rendered within that HTML element.

HTMLElement类定义了一个name属性来表示这个元素的名称,例如代表头部元素的"h1",代表段落的“p”,或者代表换行的“br”。HTMLElement还定义了一个可选属性text,用来设置 HTML 元素呈现的文本。

In addition to these two simple properties, theHTMLElementclass defines a lazy property calledasHTML. This property references a closure that combinesnameandtextinto an HTML string fragment. TheasHTMLproperty is of type() -> String, or “a function that takes no parameters, and returns aStringvalue”.

除了上面的两个属性,HTMLElement还定义了一个lazy属性asHTML。这个属性引用了一个将name和text组合成 HTML 字符串片段的闭包。该属性是Void -> String类型,或者可以理解为“一个没有参数,返回String的函数”。

By default, theasHTMLproperty is assigned a closure that returns a string representation of an HTML tag. This tag contains the optionaltextvalue if it exists, or no text content iftextdoes not exist. For a paragraph element, the closure would return" some text "or"", depending on whether thetextproperty equals"some text"ornil.

默认情况下,闭包赋值给了asHTML属性,这个闭包返回一个代表 HTML 标签的字符串。如果text值存在,该标签就包含可选值text;如果text不存在,该标签就不包含文本。对于段落元素,根据text是“some text”还是nil,闭包会返回" some text "或者""。

TheasHTMLproperty is named and used somewhat like an instance method. However, becauseasHTMLis a closure property rather than an instance method, you can replace the default value of theasHTMLproperty with a custom closure, if you want to change the HTML rendering for a particular HTML element.

可以像实例方法那样去命名、使用asHTML属性。然而,由于asHTML是闭包而不是实例方法,如果你想改变特定 HTML 元素的处理方式的话,可以用自定义的闭包来取代默认值。

For example, theasHTMLproperty could be set to a closure that defaults to some text if thetextproperty isnil, in order to prevent the representation from returning an empty HTML tag:

例如,可以将一个闭包赋值给asHTML属性,这个闭包能在text属性是nil时使用默认文本,这是为了避免返回一个空的 HTML 标签:

let heading=HTMLElement(name:"h1")

let defaultText="some default text"

heading.asHTML= {




// Prints "some default text"


TheasHTMLproperty is declared as a lazy property, because it is only needed if and when the element actually needs to be rendered as a string value for some HTML output target. The fact thatasHTMLis a lazy property means that you can refer toselfwithin the default closure, because the lazy property will not be accessed until after initialization has been completed andselfis known to exist.

asHTML声明为lazy属性,因为只有当元素确实需要被处理为 HTML 输出的字符串时,才需要使用asHTML。也就是说,在默认的闭包中可以使用self,因为只有当初始化完成以及self确实存在后,才能访问lazy属性。

TheHTMLElementclass provides a single initializer, which takes anameargument and (if desired) atextargument to initialize a new element. The class also defines a deinitializer, which prints a message to show when anHTMLElementinstance is deallocated.


Here’s how you use theHTMLElementclass to create and print a new instance:


var paragraph:HTMLElement? =HTMLElement(name:"p",text:"hello, world")


// Prints " hello, world"


Theparagraphvariable above is defined as anoptionalHTMLElement, so that it can be set tonilbelow to demonstrate the presence of a strong reference cycle.


Unfortunately, theHTMLElementclass, as written above, creates a strong reference cycle between anHTMLElementinstance and the closure used for its defaultasHTMLvalue. Here’s how the cycle looks:


The instance’sasHTMLproperty holds a strong reference to its closure. However, because the closure refers toselfwithin its body (as a way to referenceself.nameandself.text), the closurecapturesself, which means that it holds a strong reference back to theHTMLElementinstance. A strong reference cycle is created between the two. (For more information about capturing values in a closure, seeCapturing Values.)



Even though the closure refers toselfmultiple times, it only captures one strong reference to theHTMLElementinstance.


If you set theparagraphvariable toniland break its strong reference to theHTMLElementinstance, neither theHTMLElementinstance nor its closure are deallocated, because of the strong reference cycle:



Note that the message in theHTMLElementdeinitializer is not printed, which shows that theHTMLElementinstance is not deallocated.


Resolving Strong Reference Cycles for Closures (解决闭包引起的循环强引用)

You resolve a strong reference cycle between a closure and a class instance by defining acapture listas part of the closure’s definition. A capture list defines the rules to use when capturing one or more reference types within the closure’s body. As with strong reference cycles between two class instances, you declare each captured reference to be a weak or unowned reference rather than a strong reference. The appropriate choice of weak or unowned depends on the relationships between the different parts of your code.



Swift requires you to writeself.somePropertyorself.someMethod()(rather than justsomePropertyorsomeMethod()) whenever you refer to a member ofselfwithin a closure. This helps you remember that it’s possible to captureselfby accident.

Swift 有如下要求:只要在闭包内使用self的成员,就要用self.someProperty或者self.someMethod()(而不只是someProperty或someMethod())。这提醒你可能会一不小心就捕获了self。

Defining a Capture List (定义捕获列表)

Each item in a capture list is a pairing of theweakorunownedkeyword with a reference to a class instance (such asself) or a variable initialized with some value (such asdelegate = self.delegate!). These pairings are written within a pair of square braces, separated by commas.

捕获列表中的每一项都由一对元素组成,一个元素是weak或unowned关键字,另一个元素是类实例的引用(例如self)或初始化过的变量(如delegate = self.delegate!)。这些项在方括号中用逗号分开。

Place the capture list before a closure’s parameter list and return type if they are provided:


lazy var someClosure: (Int,String) ->String= {

    [unownedself,weakdelegate=self.delegate!] (index:Int,stringToProcess:String) ->Stringin

// closure body goes here


If a closure does not specify a parameter list or return type because they can be inferred from context, place the capture list at the very start of the closure, followed by theinkeyword:


lazy var someClosure: () ->String= {


// closure body goes here


Weak and Unowned References (弱引用和无主引用)

Define a capture in a closure as an unowned reference when the closure and the instance it captures will always refer to each other, and will always be deallocated at the same time.


Conversely, define a capture as a weak reference when the captured reference may becomenilat some point in the future. Weak references are always of an optional type, and automatically becomenilwhen the instance they reference is deallocated. This enables you to check for their existence within the closure’s body.



If the captured reference will never becomenil, it should always be captured as an unowned reference, rather than a weak reference.


An unowned reference is the appropriate capture method to use to resolve the strong reference cycle in theHTMLElementexample from earlier. Here’s how you write theHTMLElementclass to avoid the cycle:


class HTMLElement{

    let name:String

    let text:String?

    lazy var asHTML: () ->String= {

        [unowned self ] in

        if let text=self.text{


    } else {




    init(name:String,text:String? =nil) {





        print("\(name)is being deinitialized")



This implementation ofHTMLElementis identical to the previous implementation, apart from the addition of a capture list within theasHTMLclosure. In this case, the capture list is[unowned self], which means “capture self as an unowned reference rather than a strong reference”.

上面的HTMLElement实现和之前的实现一致,除了在asHTML闭包中多了一个捕获列表。这里,捕获列表是[unowned self],表示“将self捕获为无主引用而不是强引用”。

You can create and print anHTMLElementinstance as before:


var paragraph:HTMLElement? =HTMLElement(name:"p",text:"hello, world")


// Prints " hello, world "

Here’s how the references look with the capture list in place:


This time, the capture ofselfby the closure is an unowned reference, and does not keep a strong hold on theHTMLElementinstance it has captured. If you set the strong reference from theparagraphvariable tonil, theHTMLElementinstance is deallocated, as can be seen from the printing of its deinitializer message in the example below:



// Prints "p is being deinitialized"

For more information about capture lists, seeCapture Lists.


Web note ad 1