Swift comes with sorts of objects that we are able to use to write down kind declarations. All of them have their very own distinct options, upsides, and disadvantages. On this put up I’d wish 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 subjects:
- Understanding the fundamentals of enums
- Understanding 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 attainable worth of the enum is known as a “case”. Enums can both be used as a listing of instances that fashions particular (mutually unique) values or constants. For instance, we might symbolize a listing of working methods for SwiftUI apps as follows:
enum OperatingSystem {
case iOS, iPadOS, macOS, visionOS, tvOS, watchOS
}
If we have been to cross an working system to a perform or assign it to a variable, that might look a little bit like this:
// assigning a variable
var os: OperatingSystem = .macOS
// or passing to a perform
let binary = buildAppBinaryFor(.watchOS)
Since enums are top quality residents in Swift, they’ll conform to protocols, outline features, and even have computed properties. Observe you could’t add saved properties to an enum like you’ll be able to to a struct.
Enums are extremely helpful when we have to symbolize 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 simply’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. In case you needed to cross the string "easeInOut"
the compiler wouldn’t have the ability to kind examine that you simply handed a sound worth and you could possibly be bitten by typos similar to "aeseInOut"
which isn’t preferrred.
Though you’ll be able to’t leverage saved properties when utilizing enums, you’ll be able to 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 wish to create your enum values from exterior sources like if you’re decoding JSON. Having uncooked values means that you can create enum cases like this:
let os: OperatingSystem? = OperatingSystem(rawValue: "iOS")
In fact, when hardcoding the uncooked worth it will be significantly better to simply 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 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 cross totally different animation configurations which can be all grouped as attainable values below a single kind. That is tremendous handy!
In case you 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 matter.
Now that you recognize 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 manner that makes your code clearer and safer. Studying to acknowledge when an enum would make sense is a key ability that can actually show you how to to write down higher and safer code over time.
The record under can be utilized that will help you work out whether or not an enum matches your present use case:
- Enums are good when a variable can solely take a restricted set of predetermined values. In case you’re coping with choices, states, or modes inside your software which can be finite and identified, enums assist implement this constraint with the assistance of the compiler.
- Enums are wonderful for managing state in your purposes. As an illustration, if in case you have a UI management with a number of states like lively, inactive, disabled, and many others., an enum ensures you deal with all attainable states whereas additionally stopping builders from passing inconceivable or incorrect states.
- In case you’re utilizing constants which can be intently 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 an increasing number of assured in your capability to know whether or not an enum is sensible on your use case. I believe it’s essential to grasp that not the whole lot 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 instances might be too giant and also you’re now not grouping intently associated values collectively. It might make sense to refactor your giant record of instances right into a smaller record that makes use of related values to group sub-values collectively.
It’s additionally a good suggestion to maintain a detailed eye on how Apple makes use of enums in Swift and SwiftUI themselves. Utilizing enums for comparable eventualities ought to provide you with some confidence that you simply’re selecting the best software for the job.
And when doubtful, discuss with the record above and belief your instincts; they could be higher than you assume.