Struct, Class & Protocol in Swift

Hello iOS developers!!!

Nipuni Perera
5 min readMay 24, 2022

“Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is concise yet expressive, and Swift includes modern features developers love. Swift code is safe by design, yet also produces software that runs lightning-fast.” -Apple Inc.

Encapsulation was limited to dealing with classes back when Objective-C was the only language available. Enums, structs, and classes are the three options for current Swift programming on iOS and macOS.
These sorts, when combined with protocols, allow for extraordinary results. While these personalities have many similarities, they also have significant distinctions.

It’s All About Those Types

Swift’s safety, quickness, and simplicity are three major selling features.

It’s tough to build code that runs amok, corrupting memory and causing hard-to-find problems, which is what safety means. Swift makes your work safer by attempting to make it evident when you have a defect by displaying issues at compile time rather than leaving you hanging at runtime.

The Swift type system is the key to making this happen:

Despite the fact that there are only six Swift types, they are quite powerful. That’s true, unlike many other languages, Swift only has six built-in types.

These consist of four named types: protocol, enum, struct , and class. There are two compound types as well: tuple and function.

There are those other things that you might think of as basic types, such as Bool, Int, UInt, Float, etc. These, on the other hand, are constructed from named types and given as part of the Swift Standard Library.

Classes vs. Structs

This is a fundamental distinction: classes are reference types, but structs are value types. Here’s what’s going on:

  • When you copy a value type (for example, when it’s assigned, initialized, or passed into a function), each instance preserves a unique copy of the data.
  • When you update one instance, it does not affect the other.
    When you copy a reference type, the data is shared by all instances. The reference is transferred but not the data it refers to. When you adjust one, it affects the other.

Classes are reference types in Swift, whereas structs are value types. When you clone a struct, the data is duplicated twice. When you duplicate a class, you get two pointers to the same data instance. This is a significant distinction that influences whether you use classes or structs.

The difference between value and reference types can be remembered by remembering that a value type copies the value and a reference type copies the reference.

When Should You Use Structs?

By default, Swift recommends the use of struct. Structures are also useful in these situations:

When Should You Use Classes?

If you require a class’s special features, it is advised that you utilize one. This is why structs are the default and classes are an intentional decision.
Classes have a few additional features that structs lack:

Based on our discussion of identity and references, we may conclude that classes are preferable in the following scenarios:

  • Copying Doesn’t Make Sense

When it makes no sense to copy or compare instances, such as with a Window or UIViewController. It’s pointless to replicate an app window because there can only be one active at a time, and it’s also pointless to clone a view controller because you’d just create a new one.

  • External Effects or Data

When an instance’s lifetime is linked to external effects, such as a DatabaseConnection or TemporaryFile. It makes no sense to produce two copies of a disk reference; after all, they both refer to the same data and represent that data in code.

  • Intermediaries

When instances are only used to transport external states, such as CGContext or PersistenceController. Sometimes a helper or wrapper class is required to complete a task, such as an API or a reference to an online resource. In some circumstances, the class is merely a conduit, something that relays information, and it makes no sense to duplicate it.

To recap, it’s a good idea to utilize classes if you want capabilities that only classes give, such as inheritance, identity, Objective-C compatibility, and situations when copying a variable isn’t practical.

Protocols vs Class vs Struct

When Apple announced the introduction of Swift, the first protocol-oriented language, at their Worldwide Developers Conference (WWDC) in 2015, it signaled a departure from their previous object-oriented programming language, Objective-C.

However, because Objective-C uses implicitly shared inheritance, generating new objects becomes a tedious operation, and the resulting objects frequently include unwanted functionalities. If a class hierarchy is complicated, maintaining it might lead to issues like inefficiency and race situations.

With Swift’s protocol paradigm, developers may now create objects without inheritance, reuse objects from existing code, and interact with numerous protocols without the requirement for inheritance.

  • Swift protocols enable communication across unrelated objects by defining the methods and variables found in classes, enums, and structs. Protocols are similar to interfaces and structures are similar to classes, however they are passed by value when passed from one variable/function to another.
  • A protocol/protocol, in its most basic form, explains what an unknown sort of item can accomplish. You might argue it has two or three different sorts of attributes, as well as methods. However, such protocol never contains anything within the methods or offers actual storage for the attributes, such as class.
  • Classes are physical entities. While they may adopt protocols — that is, declare they implement the necessary attributes and methods — they are not compelled to do so. Classes may be used to generate objects, whereas protocols are just typed declarations.
  • Protocols are similar to abstract definitions, but classes and structs are actual objects that may be created.
  • Swift protocols enable communication across unrelated objects by defining the methods and variables found in classes, enums, and structs.
  • Protocols function similarly to interfaces. Structs are similar to classes in that they are transmitted by value from one variable/function to another.

Thank you very much for reading!

I’ll hope to get back to you with another interesting article…

Stay Safe!!! 👋

-Nipuni Perera-

--

--

Nipuni Perera

As a Software Engineering undergrad at the University of Kelaniya SL , I share insights on coding, dev methodologies & emerging tech. Join me on my journey!