In Swift combine what is Set<AnyCancellable>? Can I use [AnyCancellable] instead?
- User
In Swift combine what is Set? Can I use [AnyCancellable] instead?
Assistant
In Swift Combine,
Set<AnyCancellable>is a common pattern used to store and manage subscriptions so they are not cancelled prematurely.What is
Set<AnyCancellable>?AnyCancellableis a type-erased wrapper for any subscription that you can cancel (e.g., from.sink,.assign, etc.).- When you subscribe to a publisher using
.sink(receiveValue:)or.assign(to:on:), you get back a subscription object that conforms toCancellable. - To prevent the subscription from being cancelled immediately when it goes out of scope, you must store it.
Set<AnyCancellable>is used to collect and retain these subscriptions.
Example:
class MyViewModel { private var cancellables = Set<AnyCancellable>() func fetchData() { somePublisher .sink(receiveValue: { value in print(value) }) .store(in: &cancellables) // Automatically adds to the set } }The
.store(in:)method is a convenience from Combine that adds theAnyCancellableto aSet<AnyCancellable>.
Can I use
[AnyCancellable]instead?Technically yes, but it's not recommended.
Here’s why:
Aspect Set<AnyCancellable>[AnyCancellable]Uniqueness Ensures no duplicates Allows duplicates Memory Management Designed for this use case Possible memory leaks if not managed carefully Combine Support Has built-in .store(in:)No built-in support Performance Efficient insertion/removal Appending is fine, but removing specific ones is harder Best Practice ✅ Recommended by Apple ⚠️ Not standard Problems with
[AnyCancellable]:- You can accidentally add the same subscription multiple times.
- No built-in
.store(in:)method (it only works withSet). - You’d have to manually append:
You’d need to do:var cancellables: [AnyCancellable] = [] somePublisher .sink { value in ... } .store(in: &cancellables) // ❌ Won't compile!let cancellable = somePublisher.sink { ... } cancellables.append(cancellable)
✅ Best Practice
Use
Set<AnyCancellable>:class MyViewModel { private var cancellables = Set<AnyCancellable>() func subscribe() { somePublisher .sink(receiveValue: { value in print(value) }) .store(in: &cancellables) // ✅ Correct and clean } }The subscriptions are automatically retained until:
- The
Setis deallocated (i.e., the owning object is deallocated), or - You manually remove them (rarely needed).
Summary
- ✅ Use
Set<AnyCancellable>— it's the standard, safe, and intended way. - ❌ Avoid
[AnyCancellable]— it lacks Combine integration and can lead to issues. - The
.store(in:)method only works withSet<AnyCancellable>.
So, while you can use an array, you shouldn't — use
Set<AnyCancellable>instead.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.