How to use Enumeration with swift

In this tutorial, we will explain about swift significance. Here we will teach you about Swift, Apple’s new programming language for developing apps. We will be discovering some tips, tricks, and techniques that you can pursue to create your Swift code even Swiftier. Swift was considered with safety, clarity, and stability in mind, and we will use numerous of Swift’s key features to achieve these goals.

To get started, update the Xcode to a new version and create a Playground file. You won’t require a starter project to follow this tutorial. I will just walk you through the code and test it using Playgrounds.

Enumerations

Enumerations, or enums, are a special type of value in Swift that permits you to symbolize multiple cases, or possibilities. Enums are related to Bool in that enum values have to be one of multiple cases. Bool can only be true or false, but enums can be any of the cases you classify. Let’s take a look.

Imagining you have open Xcode’s Playgrounds, now we start by declaring an enum:

enum DownloadStatus {

    case downloading

    case finished

    case failed

    case cancelled

}

As you can observe, declaring an enum is simple. In the above mentioned example, we have declared a new enum called DownloadStatus with the following cases, downloading, finished, failed and cancelled.

We can use our enum in other types such as String or Int:

var currentStatus = DownloadStatus.downloading
Additional Notes:

Here you have a doubt why you need to use enum to classify the direction. Perhaps you are thinking why you can’t declare direction as an array with the four items like this:

let downloadStatus = [“downloading”, “finished”, “failed”, “cancelled”]
 let currentStatus = downloadStatus[0]

By executing this, there are two disadvantages here.

Until you refer to the downloadStatus array, you don’t have idea about what downloadStatus[0] is.  If you relate downloadStatus[0] to DownloadStatus.downloading, it is very clear that the latter is more legible.

You can actually allocate whatever string value to the variable. You can’t limit the value to “downloading”, “finished”, “failed” and “cancelled”, until you execute some extra validations. When enum is used, we can only situate myDirection to .downloading, .finished, .failed or .cancelled, but nothing else.

In this case, while declaring enums, the actual name of the enum ( DownloadStatus) should start with a capital letter. Moreover, it should be singular. This means that naming our enum downloadStatus or DownloadStatuses would be grammatically wrong. It is essential to pursue consistencies and conventions when programming, and this is one that should be commonly followed.

Moreover, our enum cases should start with lowercase letters, as of Swift 3. Prior to Swift 3, the convention was to capitalize enum cases, but that has modified. If you’re developing with Swift 3 or higher, ensure that your enum cases start with lowercase letters.

Now you clear with enum.

Let’s shows how to use them. Swift permits us to switch over enums. Look a glance:

let currentStatus = DownloadStatus.downloading

 

switch currentStatus {

case .downloading:

    print("Downloading...")

    

case .finished:

    print("Just finished the download...")

    

case .failed:

    print("Failed to download the file...")

    

case .cancelled:

    print("The download is cancelled...")

}

This permits us to write a conditional statement that’s much more powerful than a simple if statement. The compiler will enforce that we handle each of the cases in our enum in our switch statement, ensure that we don’t leave out any possible cases. This contributes to the overall safety of our code, making sure we don’t miss anything.

Up to this, you may be thought that enums don’t really include new functionality to Swift. Sure, they can form our code safer, but forever you might use a String or a few Bools to signifies data stored by an enum. Now, let’s stare at one of the most influential features of Swift enums: associated values. Associated values permit us to store additional data within an enum. Let’s declare a new enum, called WeatherCondition, that permits us to state a weather condition, along with some additional information:

enum Cloud {

    case cirrus

    case cumulus

    case altocumulus

    case stratus

    case cumulonimbus

}

 

enum WeatherCondition {

    case sunny(temperature: Float)

    case rainy(inchesPerHour: Float)

    case cloudy(cloudType: Cloud, windSpeed: Float)

}

In this example, we declared 2 enums: Cloud and WeatherCondition. Don’t give much attention to the Cloud enum. Alternatively, stare at the WeatherCondition declaration. We declared 3 cases, and each of them stores some type of extra information aside from the case of the enum itself. In our sun case, we store an Int, called temperature. In our rain case, we store a Float, called inchesPerHour, in our cloud case, we store 2 values: cloudType, a Cloud, and wind, a Float.

In enums, it is easy to store extra information in the associated values. Here you can look how to use them:

let currentWeather = WeatherCondition.cloudy(cloudType: .cirrus, windSpeed: 4.2)

In enum cases we can switch on associated value, just like we can on normal ones:

switch currentWeather {
case .sun(let temperature):
 print("It is sunny and the temperature is \(temperature).")
 
case .rain(let inchesPerHour):
 print("It is raining at a rate of \(inchesPerHour) inches per hour.")
 
case .cloud(let cloudType, let windSpeed):
 print("It is cloud; there are \(cloudType) clouds in the sky, and the wind speed is \(windSpeed).")
}

I hope, you can observe the value that enums included to your app. They can form your code safer, clearer and more summarized. Though you may know about enum already, but were unware of the associated values they offer, or how to switch over them. Despite, try to integrate them into your apps, as they’re exceptionally useful.

Last Update: September 11, 2018  

September 11, 2018   255   Nandini Ramachandran    Swift Significance    
Total 0 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
INSTAGRAM
LinkedIn