はじめに
SwiftのEnumはかなり洗練されていますが、Dartでも同じようなことがいくつかできるので、頻繁に使うSwiftのEnumの機能をDartで書き直してみます。
実行環境はこちらです。
Flutter: 3.3.10
Dart: 2.18.6
Xcode: 14.2
Swift: 5.7
値付きEnum
Swift
enum DogType: Int {
case shiba = 1
case chiwawa = 2
case pudoru = 3
}
print(DogType.chiwawa.rawValue) // 2
Dart
enum DogType {
shiba(value: 1),
chiwawa(value: 2),
pudoru(value: 3);
final int value;
const DogType({
required this.value,
});
}
main() {
print(DogType.chiwawa.value); // 2
}
プロトコルに準拠させる
Swift
protocol Animal {
func displayName() -> String
}
enum DogType: Int {
case shiba = 1
case chiwawa = 2
case pudoru = 3
}
extension DogType: Animal {
func displayName() -> String {
switch self {
case .shiba:
return "しば"
case .chiwawa:
return "チワワ"
case .pudoru:
return "プードル"
}
}
}
print(DogType.chiwawa.displayName()) // チワワ
Dart
abstract class Animal {
String displayName();
}
enum DogType implements Animal {
shiba(value: 1),
chiwawa(value: 2),
pudoru(value: 3);
final int value;
const DogType({
required this.value,
});
@override
String displayName() {
switch (this) {
case DogType.shiba:
return "しば";
case DogType.chiwawa:
return "チワワ";
case DogType.pudoru:
return "プードル";
}
}
}
main() {
print(DogType.chiwawa.displayName()); // チワワ
}
Extension
Swift
enum DogType: Int {
case shiba = 1
case chiwawa = 2
case pudoru = 3
}
extension DogType {
func displayName() -> String {
switch self {
case .shiba:
return "しば"
case .chiwawa:
return "チワワ"
case .pudoru:
return "プードル"
}
}
}
print(DogType.chiwawa.displayName()) // チワワ
Dart
enum DogType {
shiba(value: 1),
chiwawa(value: 2),
pudoru(value: 3);
final int value;
const DogType({
required this.value,
});
}
extension DogTypeExtension on DogType {
String displayName() {
switch (this) {
case DogType.shiba:
return "しば";
case DogType.chiwawa:
return "チワワ";
case DogType.pudoru:
return "プードル";
}
}
}
main() {
print(DogType.chiwawa.displayName()); // チワワ
}
全ての値を列挙する
Swift
enum DogType: Int, CaseIterable {
case shiba = 1
case chiwawa = 2
case pudoru = 3
}
print(DogType.allCases) // [DogType.shiba, DogType.chiwawa, DogType.pudoru]
Dart
enum DogType {
shiba(value: 1),
chiwawa(value: 2),
pudoru(value: 3);
final int value;
const DogType({
required this.value,
});
}
main() {
print(DogType.values); // [DogType.shiba, DogType.chiwawa, DogType.pudoru]
}
終わりに
Swiftほど多機能ではないですが、Dartでも上記で挙げたような頻繁に使う機能は網羅されています。
以上です。