What are enums in Swift? – Donny Wals


Swift comes with kinds of objects that we are able to use to put in writing kind declarations. All of them have their very own distinct options, upsides, and drawbacks. On this put up I’d prefer to zoom in on the enum kind so you may get a way of what enums are, and when they are often helpful.

On this put up we’ll cowl the next matters:

  • Understanding the fundamentals of enums
  • Figuring out when an enum must be used
  • Avoiding enum overuse

Let’s soar proper in!

Understanding the fundamentals of enums

In Swift, enums are values varieties which can be declared utilizing the enum key phrase. Each potential worth of the enum is named a “case”. Enums can both be used as an inventory of circumstances that fashions particular (mutually unique) values or constants. For instance, we may signify an inventory of working techniques for SwiftUI apps as follows:

enum OperatingSystem {
  case iOS, iPadOS, macOS, visionOS, tvOS, watchOS
}

If we had been to go an working system to a perform or assign it to a variable, that may look a bit of like this:

// assigning a variable
var os: OperatingSystem = .macOS

// or passing to a perform
let binary = buildAppBinaryFor(.watchOS)

Since enums are firstclass residents in Swift, they’ll conform to protocols, outline capabilities, and even have computed properties. Be aware that you could’t add saved properties to an enum like you possibly can to a struct.

Enums are extremely helpful when we have to signify a finite set of predefined states. With a enum, it’s unimaginable to create or use state that aren’t right which will be extremely helpful. Think about that you just’d must manually kind out an animation kind as a string in SwiftUI as a substitute of passing .easeInOut and realizing that in case your code compiles you handed an accurate animation kind. If you happen to needed to go the string "easeInOut" the compiler wouldn’t have the ability to kind examine that you just handed a legitimate worth and you would be bitten by typos similar to "aeseInOut" which isn’t superb.

Although you possibly can’t leverage saved properties when utilizing enums, you possibly can affiliate values with enums and you’ll give them uncooked values.

An enum with uncooked values appears to be like like this:

enum OperatingSystem: String {
  case iOS = "iOS"
  case iPadOS = "iPadOS"
  case macOS = "macOS"
  // and so on...
}

On this case, my uncooked enum values match the enum case names straight. Which means that as a substitute of including each potential worth after the case identify, I can specify that my enum makes use of a uncooked String worth with out modifying my circumstances:

enum OperatingSystem: String {
  case iOS, iPadOS, macOS, visionOS, tvOS, watchOS
}

Defining enums with uncooked values is extremely helpful once you wish to create your enum values from exterior sources like once you’re decoding JSON. Having uncooked values permits you to create enum cases like this:

let os: OperatingSystem? = OperatingSystem(rawValue: "iOS")

In fact, when hardcoding the uncooked worth it could be significantly better to only use .iOS straight but when the uncooked worth comes from an exterior supply we are able to attempt to make an enum with the worth we obtained. If this works, we get an enum case again and if not, we get nil. This occurs once we go a uncooked worth that’s not outlined on the enum.

The very last thing I’d like to point out you earlier than we speak about up and draw back of enums is defining an enum with an related worth.

An instance of such an enum is Swift’s built-in Outcome kind:

enum Outcome<Success, Failure: Error> {
    case success(Success)
    case failure(Failure)
}

This enum makes use of generics to permit builders to make use of customized values for Success and Failure however you may also outline an enum with out generics for related values. For instance:

enum Animation {
  case none
  case easeIn(period: CGFloat)
  // ...
}

With this Animation enum we are able to go completely different animation configurations which can be all grouped as potential values below a single kind. That is tremendous handy!

If you happen to get to a degree the place you’d like to check some worth to an enum case that has an related worth, you’ll wish to learn up on if case let syntax utilizing this put up I’ve on that subject.

Now that you already know a bit about what enums are, let’s talk about when it is sensible to make use of them.

Figuring out When to Use an Enum

Enums are perfect for managing a set group of associated values in a method that makes your code clearer and safer. Studying to acknowledge when an enum would make sense is a key talent that can really show you how to to put in writing higher and safer code over time.

The listing under can be utilized that can assist you work out whether or not an enum matches your present use case:

  • Enums are excellent when a variable can solely take a restricted set of predetermined values. If you happen to’re coping with choices, states, or modes inside your utility which can be finite and identified, enums assist implement this constraint with the assistance of the compiler.
  • Enums are glorious for managing state in your purposes. As an example, in case you have a UI management with a number of states like energetic, inactive, disabled, and so on., an enum ensures you deal with all potential states whereas additionally stopping builders from passing unimaginable or incorrect states.
  • If you happen to’re utilizing constants which can be carefully associated and must be grouped below a single kind, enums make this group clear and logical. For instance, error varieties, configuration choices, and different comparatively brief finite lists of values.

Over time you’ll develop increasingly more assured in your capability to know whether or not an enum is sensible in your use case. I believe it’s essential to grasp that not all the things can or must be represented as an enum.

For instance, I believe it’s smart to be sure that your enums are pretty small. An enum that holds dozens of circumstances might be too massive and also you’re not grouping carefully associated values collectively. It may make sense to refactor your massive listing of circumstances right into a smaller listing that makes use of related values to group sub-values collectively.

It’s additionally a good suggestion to maintain an in depth eye on how Apple makes use of enums in Swift and SwiftUI themselves. Utilizing enums for related eventualities ought to provide you with some confidence that you just’re choosing the proper instrument for the job.

And when doubtful, check with the listing above and belief your instincts; they is perhaps higher than you assume.

Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Stay on op - Ge the daily news in your inbox