Skip to content

Why are structs with closure vars are used instead of protocols? #522

Answered by mbrandonw
surajbarkale asked this question in Q&A
Discussion options

You must be logged in to vote

In addition to what @mstfy posted, there's a full collection of material on the subject here and here.

There are many reasons to use a struct over a protocol (if possible), but I can distill one example for you. The main reason one puts an interface in front of a dependency (whether it be via structs or protocols) is so that you can create multiple instances of the dependency that serve different purposes. The most common are:

  • You can have a "live" instance that runs the real code under the hood (e.g. audio player, location manager, database, etc.), which is what you would use in the production app.
  • You can have a "mock" instance that returns some mock data immediately rather than reachi…

Replies: 3 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by surajbarkale
Comment options

You must be logged in to vote
1 reply
@surajbarkale
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants