Switch Statement

From SwiftAPI

Jump to: navigation, search

Contents

Java

int x = 2;
int y;
switch(x) {
    case 1:
        y = 1;
        break;
 
    case 2:
        y = 4;
        break;
 
    default:
        y = 8;
}
// y == 4

JavaScript

var x = 2;
var y;
switch(x) {
    case 1:
        y = 1;
        break;
 
    case 2:
        y = 4;
        break;
 
    default:
        y = 8;
}
// y == 4

Perl

Perl 5.10+:

use feature "switch";
 
$x = 2;
given($x) {
    when (1) {
        $y = 1;
    }
 
    when (2) {
        $y = 4;
    }
 
    default {
        $y = 8;
    }
}
# $y == 4

PHP

php.net

$x = 2;
switch($x) {
    case 1:
        $y = 1;
        break;
 
    case 2:
        $y = 4;
        break;
 
    default:
        $y = 8;
}
// $y == 4

Ruby

x = 2
case x
    when 1
        y = 1
 
    when 2
        y = 4
 
    else
        y = 8
end
# $y == 4

Swift

let x = 2
var y = 0
switch x {
    case 1:
        y = 1

    case 2:
        y = 4

    default:
        y = 8
}
// y == 4

Visual Basic .NET

Dim x As Integer = 2
Dim y As Integer
Select Case x
    Case 1
        y = 1
    Case 2
        y = 4
    Case Else
        y = 8
End Select
' y = 4
Personal tools