Have any Question?

You can ask below or enter what you are looking for!

Beginner’s guide to Enum in Swift

What is Enum

Enum is a data structure that can only has discrete values.

It is always used if you need to store a group of related values like directions on map or compass(North, East, West, South), status of download process (Completed, Cancelled, Paused, Downloading) and so on.

enum Direction {
        
     case North
     case South
     case East
     case West
}

Enums are VALUE TYPE just like struct so they are copied when passed around

Unlike C and Objective C, Enums in Swift does not have an associated integer value with every state but it provides associated data which is much more powerful as you will see later.

In Swift Enums are first class citizens, so they can conform to protocols, provide instance methods and properties but only computed properties are allowed.



Check Enum’s cases

We don’t use == to check for enum cases, instead we use SWITCH and we must handle all cases or at least use a default for cases you are not interested in

        var direction = Direction.East
        
        switch direction {
        case .East:
            print("east")
        case .North:
            print("north")
        default:
            print("other direction")
        }

Enum with Associated Data

In Swift each enum’s state can also has associated data of any given type

enum DownloadStatus {
        case Downloading(percentage: Int)
        case Completed(filename: String, filesize: Int)
        case Paused
        case Cancelled
}

Here we create one case with one Int, and another case with String and Int because they don’t have to be all of the same type

You can also create it without names like this

case Completed(String, Int)

Then you can create a completed status with file name and size like this

var status = DownloadStatus.Completed("enum.h", 3890)

Use “let” to access Enum’s associated data within Switch statement

    switch status {
        case .Completed(let name, let size):
            print("\(name)--\(size)")
        default:
            print("not completed")
    }

You don’t have to use the same names you used in Enum’s declaration

You might like reading about InOut parameters in Swift

Leave a Reply

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