飞镖交替很多 if elseif

Jon*_*ona 4 if-statement dart flutter

我想用另一个字符串替换 Dart 中的 URL 字符串。例子:

if (url == "http://www.example.com/1") {
home = "example";
} else if (url == "http://www.example.com/2") {
home = "another example";
}
Run Code Online (Sandbox Code Playgroud)

难道没有更好的方法,代码更少,速度更快吗?我必须这样做超过 60 次..

Mul*_*dec 6

如果你想要更少的代码,你可以这样做:

homes = {
  "http://www.example.com/1": "example",
  "http://www.example.com/2": "another example",
  "http://www.example.com/3": "yet another one",
};
home = homes[url];
Run Code Online (Sandbox Code Playgroud)


atr*_*eon 5

我喜欢 Muldec 的回答,因为我个人觉得 switch 语句读起来有点尴尬。我也喜欢有默认值的选项,这样您就可以“某种程度上”重新定义 switch 语句。额外的好处是您可以将它内联用作表达式,并且它仍然是类型安全的......就像这样。

case2(myInputValue,
  {
    "http://www.example.com/1": "example",
    "http://www.example.com/2": "another example",
    "http://www.example.com/3": "yet another one",
  }, "www.google");
Run Code Online (Sandbox Code Playgroud)

case2 代码可以是

TValue case2<TOptionType, TValue>(
  TOptionType selectedOption,
  Map<TOptionType, TValue> branches, [
  TValue defaultValue = null,
]) {
  if (!branches.containsKey(selectedOption)) {
    return defaultValue;
  }

  return branches[selectedOption];
}
Run Code Online (Sandbox Code Playgroud)