Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift enums that call a method

Tags:

enums

swift

Say I have an enum like this:

enum ItemType {
    case TypeOne
    case TypeTwo
    case TypeThree
}

Then I have a method that calls another method based on the ItemType chosen:

func getItem(withType: ItemType) {
    switch withType {
        case TypeOne:
            getTypeOneItem()
        case TypeTwo:
            getTypeTwoItem()
        case TypeThree:
            getTypeThreeItem()
    }
}

I'm just wondering if there is a better way to write this, if I have a lot of ItemTypes the switch statement would get very messy.

Not sure if it's possible but maybe an enum that calls the method directly enum xx { case TypeOne: ?? = getTypeOneItem() ...

like image 667
matt Avatar asked Sep 15 '25 18:09

matt


1 Answers

An easy solution for that is using the enum as the key of a dictionary. Suppose they are all void. You can do something like this:

import Foundation

enum ItemType
{
    case TypeOne
    case TypeTwo
    case TypeThree
}

func getTypeOneItem() -> Void
{
    print("One")
}

func getTypeTwoItem() -> Void
{
    print("Two")
}

func getTypeThreeItem() -> Void
{
    print("Three")
}

// Register all the enum values
let dict =  [ItemType.TypeOne: getTypeOneItem, ItemType.TypeTwo: getTypeTwoItem, ItemType.TypeThree: getTypeThreeItem]

// Fetch
let function1 = dict[ItemType.TypeOne]!

function1() // This prints "One"

To me, it looks cleaner than using switch.

like image 187
brduca Avatar answered Sep 17 '25 09:09

brduca