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() ...
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.
Insert the function to the enum itself. You do not need a parameter anymore. You could even add it to the type with static
, but that would not make sense, since you always need a variable of type ItemType
.
func getTypeOneItem() -> Void {
print("typeOne")
}
func getTypeTwoItem() -> Void {
print("typeTwo")
}
func getTypeThreeItem() -> Void {
print("typeThree")
}
enum ItemType {
case TypeOne
case TypeTwo
case TypeThree
func getItem() -> Void {
switch self {
case .TypeOne:
getTypeOneItem()
case .TypeTwo:
getTypeTwoItem()
case .TypeThree:
getTypeThreeItem()
}
}
}
let item: ItemType = ItemType.TypeOne
item.getItem() // prints typeOne
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.