Swift Strong and Weak References

Ramesh Chavan
1 min readOct 4, 2022

--

In Swift, ARC (Automatic Reference Counting) automatically handles the allocation and deallocation of memory.

However, we can prevent ARC to automatically dellocate memory by specifying the type of reference.

For example,

A strong reference keeps a firm hold on instances and doesn’t allow deallocation by ARC.

Similarly, A weak reference cannot protect the instances from being deallocated by ARC.

Note: The declaration of a property is strong by default. To declare a weak reference we use the weak keyword.

Strong Reference in Swift

In Swift, whenever we create an instance of a class, a reference count value is increased from 0 to 1. Similarly, if we dellocate the instance the count is decreased to 0.

Swift Weak Reference

As mentioned earlier, a weak reference doesn’t protect the object from being deallocated. This is because when we declare a property as weak, the reference count of that property will never be more than 1.

class Employee {
weak var colleague: Employee?
...
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ramesh Chavan
Ramesh Chavan

Written by Ramesh Chavan

Like to work on iOS, Android, UIPath and Graph DB

No responses yet