UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Why do we use array.removeAll(keepingCapacity: true) all the time?

Forums > 100 Days of Swift

It seems that in all of the projects I've done in this course so far, Paul always tells us to use array.removeAll(keepingCapacity: true) when deleting all the items from our arrays. But, in Apple's documentation, it says that keepingCapacity is set to false by default. So, why do we always change it? It seems that when I change it to false to test the projects, they still work just fine.

So, is this just for some invisible preformance reasons that make the code more efficient? If so, why does apple set this to false by default if it is more efficient to use true all the time?


@twostraws  Site AdminHWS+

Defaults are usually based on the principle of least surprise: for any given situation, they use whatever is simplest, and least likely to cause problems.

When removing all the items from an array, I think freeing up the space is the right thing to do by default – if you clear an array that was holding 10 million integers, you'd be pretty surprised to see it was still holding on to a fair chunk of memory.

Sometimes, though, we have extra information. For example, if you know the integer array is being cleared but will be refilled almost immediately, you can choose to keep the capacity for performance reasons.

So, Swift does what is simple and safe by default, but leaves open the alternative for times when we know we'll want that capacity again.


Thanks paul , nice to know you keep an eye on the forum in between your busy schedule ...


Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.