Enumerations aka Enums

Enumerations in Swift define a common type for a group of related values. Unlike other languages, enumerations in Swift don’t have to provide a value for each case. The case keyword is used to define new enumeration cases.

    enum Direction {
    	case left
    	case right
    	case forward
    	case backward
    // Enum type is inferred
    var characterDirection = Direction.right
    characterDirection = .forward

An enumeration name has to start with a capital letter as shown above. The type of enum is inferred on initialization and can be passed a shorter syntax .forward once declared.

Associated value

It is sometimes valuable to store variables or types within these enums to use later. This is what associated values are used for.

    enum ApiError: Error {
    	case requestFailed
    	case responseUnsuccessful(statusCode: Int)

One of the things I like about swift enumerations is how they are matched. Suppose we have a function that has an Enum as a parameter.

    func move(direction:Direction) {
    		switch direction {
    			case .left:
    				print("move left")
    			case .right:
    				print("move right")
    			case .forward:
    				print("move forward")
    			case .backward:
    				print("move backward")

When the function is called and the argument is passed we simply pass it as .forward instead of having to pass it as Direction.forward.

Leave a Reply