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() ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With