Dartの勉強6−2:条件分岐(if-caseとswitch)
条件分岐の2としてif-caseとswitchを扱います。コードを見た方が早いので下をご覧ください。
- if-case
void main() { var pair = [2, 5]; if (pair case [int x, int y]) { print('Was coordinate array $x,$y'); //エラーにならずこちらが表示 } else { throw FormatException('Invalid coordinates.'); } } void main() { var pair = [2, 5, 1]; if (pair case [int x, int y]) { print('Was coordinate array $x,$y'); } else { throw FormatException('Invalid coordinates.'); //エラーとなってこちらが表示 } }ということで、変数のパターンを判別してくれます。
- switch
void main() { var color = 'Blue'; switch (color) { case 'Green': print("緑"); continue yellowCase; //Greenではない場合、yellowCaseに飛びます。違ったら戻ってきます。 case 'Blue'://処理を記述しないと、次のcaseの処理を行います。 case 'Black': print("青か黒"); case 'Red': print("赤"); yellowCase: case 'Yellow': print("黄"); default: print("違う色"); } }colorにいろんな値を入れてみて試してください。