Swift - Passing different enum types for same variable to a class -


how can pass different enums types same variable, identify type later , use raw values operations?

i have 2 enums menu1 , menu2 of type string. pass array of enums class shows submenu. pass enum same variable since may add menu in future.

for applying abstraction, use protocol, follows:

protocol menu {}  enum menu1: string, menu {     case option1 = "option 01 menu 01"     case option2 = "option 02 menu 01"     case option3 = "option 03 menu 01"     case option4 = "option 04 menu 01"     case option5 = "option 05 menu 01" }  enum menu2: string, menu {     case option1 = "option 01 menu 02"     case option2 = "option 02 menu 02"     case option3 = "option 03 menu 02"     case option4 = "option 04 menu 02"     case option5 = "option 05 menu 02" } 

by implementing this, able declare arrays of menu type, include both of enums:

let mymenu1array: [menu1] = [.option1, .option2, .option5] let mymenu2array: [menu2] = [.option1, .option3, .option4] 

for instance, function takes parameter array of menus should work:

func handlemenu(_ menuarray: [menu]) {     if let menu1array = menuarray as? [menu1] {         print("menu 1 detected!")          // iterate through instance...         option in menu1array {             print(option.rawvalue)         }          return     }      if let menu2array = menuarray as? [menu2] {         print("menu 2 detected!")          // iterate through instance...         option in menu2array {             print(option.rawvalue)         }          return     } } 

the output be:

handlemenu(mymenu1array) /*  menu 1 detected!  option 01 menu 01  option 02 menu 01  option 05 menu 01  */  handlemenu(mymenu2array) /*  menu 2 detected!  option 01 menu 02  option 03 menu 02  option 04 menu 02  */ 

so, if have property in class should represents menu, declare type of menu:

class  myclass {     ...      var menu: menu?      ... } 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -