[swift-users] Class vs Structures

Brent Royal-Gordon brent at architechies.com
Fri Jun 30 21:10:36 CDT 2017

> On Jun 29, 2017, at 10:40 AM, Vitor Navarro via swift-users <swift-users at swift.org> wrote:
> Do you guys have any guideline regarding usage here?

Here's my suggestion: Use a class when the object represents a specific *thing* that can't be duplicated without consequence; use a struct (or enum) when the instance represents some abstract data with no concrete existence. Some examples using framework types:

* A piece of text is just some data; duplicating it doesn't do anything except maybe use more memory. So `String` should be a struct.

* A label is a particular thing that exists at a particular place on screen; if you duplicated it, you'd end up with two labels on the screen, or with an off-screen copy of a label that wouldn't have any effect when you mutated it. So `UILabel` should be a class.

* A URL is just some data; if you construct two URLs with the same contents, they are completely interchangeable. So `URL` should be a struct.

* A connection to a web server to retrieve the contents of a URL is a particular thing; if you duplicated it, you would either establish another connection, or the two instances would interfere with each other (e.g. canceling one would cancel the other). So `URLSessionTask` and `NSURLConnection` are classes.

Sometimes the same problem, approached in slightly different ways, would allow you to use either one. For instance, a database record is a particular *thing* and should probably be a class, but copy the values of the fields (perhaps omitting the ID) out of it and suddenly you have a plausible struct. As a *general* rule, it's usually better to use structs where possible because it's easier to reason about their behavior—mutations in one function don't suddenly pop up in a totally unrelated function—but sometimes a particular type works very easily as a class and very awkwardly as a struct. Ultimately, it's a judgement call.

The other point I will make is this: "Protocol-oriented programming" is new and exciting and often very useful, but it's a tool, not a religion. If subclassing works well for your use case, then subclass away.

Brent Royal-Gordon

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170630/86347e87/attachment.html>

More information about the swift-users mailing list