前端學習-Dart官方文件學習-003-模式匹配

ayubene發表於2024-05-29

官方文件連結

簡介

匹配和解構

// 匹配
const a = 'a';
const b = 'b';
switch (obj) {
  // List pattern [a, b] matches obj first if obj is a list with two fields,
  // then if its fields match the constant subpatterns 'a' and 'b'.
  case [a, b]:
    print('$a, $b');
}

// 解構
var numList = [1, 2, 3];
// List pattern [a, b, c] destructures the three elements from numList...
var [a, b, c] = numList;
// ...and assigns them to new variables.
print(a + b + c);

變數賦值

使用變數賦值模式交換兩個變數的值,而不宣告第三個臨時變數:

var (a, b) = ('left', 'right');
(b, a) = (a, b); // Swap.
print('$a $b'); // Prints "right left".

Switch

switch (obj) {
  // Matches if 1 == obj.
  case 1:
    print('one');

  // Matches if the value of obj is between the
  // constant values of 'first' and 'last'.
  case >= first && <= last:
    print('in range');

  // Matches if obj is a record with two fields,
  // then assigns the fields to 'a' and 'b'.
  case (var a, var b):
    print('a = $a, b = $b');

  default:
}

// 邏輯或在switch比較常見
var isPrimary = switch (color) {
  Color.red || Color.yellow || Color.blue => true,
  _ => false
};

// Switch 中的條件
switch (pair) {
  case (int a, int b):
    if (a > b) print('First element greater');
  // If false, prints nothing and exits the switch.
  case (int a, int b) when a > b:
    // If false, prints nothing but proceeds to next case.
    print('First element greater');
  case (int a, int b):
    print('First element not greater');
}

For and for-in loops

Map<String, int> hist = {
  'a': 23,
  'b': 100,
};

for (var MapEntry(key: key, value: count) in hist.entries) {
  print('$key occurred $count times');
}
key: key 可簡寫為 :key
for (var MapEntry(:key, value: count) in hist.entries) {
  print('$key occurred $count times');
}

在 Dart 中,MapEntry是Map中的一個內部類,它表示Map中的一個鍵值對

Map<String, int> myMap = {
  'a': 1,
  'b': 2,
  'c': 3,
};

// 獲取 Map 中的第一個鍵值對
MapEntry<String, int> firstEntry = myMap.entries.first;

// 訪問鍵和值
String key = firstEntry.key;
int value = firstEntry.value;

// 修改值
firstEntry.value = 4;

// 列印修改後的 Map
print(myMap); 

Algebraic data types(沒懂

sealed class Shape {}

class Square implements Shape {
  final double length;
  Square(this.length);
}

class Circle implements Shape {
  final double radius;
  Circle(this.radius);
}

double calculateArea(Shape shape) => switch (shape) {
      Square(length: var l) => l * l,
      Circle(radius: var r) => math.pi * r * r
    };

Validating incoming JSON

當知道JSON結構時

var json = {
  'user': ['Lily', 13]
};
var {'user': [name, age]} = json;

當JSON來自外部(如網路),需要先進行驗證

// 普通寫法
if (json is Map<String, Object?> &&
    json.length == 1 &&
    json.containsKey('user')) {
  var user = json['user'];
  if (user is List<Object> &&
      user.length == 2 &&
      user[0] is String &&
      user[1] is int) {
    var name = user[0] as String;
    var age = user[1] as int;
    print('User $name is $age years old.');
  }
}
// pattern寫法
if (json case {'user': [String name, int age]}) {
  print('User $name is $age years old.');
}

Pattern types 模式匹配型別

相關文章