Enum from String

前端 未结 18 1970
温柔的废话
温柔的废话 2020-12-15 14:54

I have an Enum and a function to create it from a String because i couldn\'t find a built in way to do it



        
18条回答
  •  醉梦人生
    2020-12-15 15:35

    Here is an alternative way to @mbartn's approach using extensions, extending the enum itself instead of String.

    Faster, but more tedious

    // We're adding a 'from' entry just to avoid having to use Fruit.apple['banana'],
    // which looks confusing.
    enum Fruit { from, apple, banana }
    
    extension FruitIndex on Fruit {
      // Overload the [] getter to get the name of the fruit.
      operator[](String key) => (name){
        switch(name) {
          case 'banana': return Fruit.banana;
          case 'apple':  return Fruit.apple;
          default:       throw RangeError("enum Fruit contains no value '$name'");
        }
      }(key);
    }
    
    void main() {
      Fruit f = Fruit.from["banana"];
      print("$f is ${f.runtimeType}"); // Outputs: Fruit.banana is Fruit
    }
    

    Less tedius, but slower

    If O(n) performance is acceptable you could also incorporate @Collin Jackson's answer:

    // We're adding a 'from' entry just to avoid having to use Fruit.apple['banana']
    // which looks confusing.
    enum Fruit { from, apple, banana }
    
    extension FruitIndex on Fruit {
      // Overload the [] getter to get the name of the fruit.
      operator[](String key) =>
        Fruit.values.firstWhere((e) => e.toString() == 'Fruit.' + key);
    }
    
    void main() {
      Fruit f = Fruit.from["banana"];
      print("$f is ${f.runtimeType}"); // Outputs: Fruit.banana is Fruit
    }
    

提交回复
热议问题