在Swift中,您可以轻松地将原始值赋给枚举,例如:
enum Game: Int {
case lol = 1
case dnf = 2
case dota = 3
}
但是,您不能在Dart中将原始值赋给枚举:
enum Game {
lol = 1,
dnf = 2,
dota = 3,
}
它显示了错误,您只能使用最简单的枚举:
enum Game {
lol,
dnf,
dota,
}
真的让我很失望。
有没有办法像Swift那样给Dart的枚举赋值?
发布于 2021-09-23 06:26:33
您可以使用枚举扩展,例如
enum EnumAction { subtract, add }
extension EnumActionExtension on EnumAction {
String get name {
switch (this) {
case EnumAction.add:
return 'add';
case EnumAction.subtract:
return 'subtract';
}
}
}
在本例中,您将返回一个int和一个int值。默认情况下,枚举也会被分配int值,即它们各自的索引。您可以调用Game.lol.index,它将返回0。
https://stackoverflow.com/questions/69294932
复制相似问题