Sunday, May 19, 2024
HomeIOS DevelopmentWhat are enums in Swift? – Donny Wals

What are enums in Swift? – Donny Wals


Swift comes with sorts of objects that we are able to use to write down sort declarations. All of them have their very own distinct options, upsides, and disadvantages. On this publish I’d prefer to zoom in on the enum sort so you may get a way of what enums are, and when they are often helpful.

On this publish we’ll cowl the next subjects:

  • Understanding the fundamentals of enums
  • Understanding when an enum needs to be used
  • Avoiding enum overuse

Let’s leap proper in!

Understanding the fundamentals of enums

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

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

If we had been to cross an working system to a operate or assign it to a variable, that will look a little bit like this:

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

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

Since enums are top quality residents in Swift, they’ll conform to protocols, outline capabilities, and even have computed properties. Word which you could’t add saved properties to an enum like you may to a struct.

Enums are extremely helpful when we have to signify a finite set of predefined states. With a enum, it’s inconceivable to create or use state that aren’t right which could be extremely helpful. Think about that you just’d should manually sort out an animation sort as a string in SwiftUI as a substitute of passing .easeInOut and understanding that in case your code compiles you handed an accurate animation sort. If you happen to needed to cross the string "easeInOut" the compiler wouldn’t have the ability to sort verify that you just handed a legitimate worth and you would be bitten by typos reminiscent of "aeseInOut" which isn’t preferrred.

Regardless that you may’t leverage saved properties when utilizing enums, you may affiliate values with enums and you’ll give them uncooked values.

An enum with uncooked values seems like this:

enum OperatingSystem: String {
  case iOS = "iOS"
  case iPadOS = "iPadOS"
  case macOS = "macOS"
  // and many others...
}

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

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

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

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

In fact, when hardcoding the uncooked worth it will be a lot 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 acquired. If this works, we get an enum case again and if not, we get nil. This occurs after we cross a uncooked worth that’s not outlined on the enum.

The very last thing I’d like to indicate 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 Consequence sort:

enum Consequence<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 can even outline an enum with out generics for related values. For instance:

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

With this Animation enum we are able to cross totally different animation configurations which can be all grouped as attainable values underneath a single sort. That is tremendous handy!

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

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

Understanding When to Use an Enum

Enums are perfect for managing a set group of associated values in a approach that makes your code clearer and safer. Studying to acknowledge when an enum would make sense is a key ability that can really assist you to to write down higher and safer code over time.

The listing beneath can be utilized that can assist you determine 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 software which can be finite and recognized, enums assist implement this constraint with the assistance of the compiler.
  • Enums are glorious for managing state in your functions. As an illustration, you probably have a UI management with a number of states like energetic, inactive, disabled, and many others., an enum ensures you deal with all attainable states whereas additionally stopping builders from passing inconceivable or incorrect states.
  • If you happen to’re utilizing constants which can be intently associated and needs to be grouped underneath a single sort, enums make this group clear and logical. For instance, error sorts, configuration choices, and different comparatively brief finite lists of values.

Over time you’ll develop increasingly more assured in your skill to know whether or not an enum is sensible on your use case. I feel it’s vital to grasp that not all the pieces can or needs to be represented as an enum.

For instance, I feel it’s clever to be sure that your enums are pretty small. An enum that holds dozens of instances might be too giant and also you’re now not grouping intently associated values collectively. It may make sense to refactor your giant listing of instances 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 comparable eventualities ought to offer you some confidence that you just’re selecting the best software for the job.

And when unsure, consult with the listing above and belief your instincts; they is likely to be higher than you suppose.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments