Member-only story

Swift Programming Tutorial: Weak References

Understand That ‘weak’ in Swift Isn’t Really Weak at All

Arc Sosangyo
4 min readDec 20, 2024
Photo by Erika Fletcher on Unsplash

The mighty yet misunderstood weak! It’s one of those words in Swift that seems unassuming but wields great power, like a wizard whispering magic to avoid memory leaks.

This article is part of my Swift Programming Tutorial series.

What is weak in Swift?

When you declare a property as weak, you’re telling Swift, “Hey, I don’t want this property to own the thing it’s pointing to. I just want to borrow it and let someone else keep the main responsibility for it.”

Here’s the deal: Swift uses ARC (Automatic Reference Counting) to manage memory. Objects can have strong references to each other, which means, “I own you, and I won’t let you go!” But if two objects own each other at the same time, it’s like a clingy couple — neither one lets the other go, and they’re stuck in memory forever. This is called a retain cycle, and it’s bad news.

Enter weak, the hero that saves the day by breaking this cycle. A weak reference doesn’t increase the reference count of the object it points to, so the object can still be deallocated when the strong references let it go.

Declaring a weak property

--

--

Arc Sosangyo
Arc Sosangyo

Written by Arc Sosangyo

Arc is an iOS Dev and app publisher, a former IT manager who transitioned to iOS engineering, and a big fan of AI, coding, science, history, and philosophy.

No responses yet