let point = (1,1);
switch point {
case (0,0):
print("(0,0) is atthe origin");
case (_,0):
print("(\(point.0),0) is on the X-axis");
case (0,_):
print("(0,\(point) is on the Y-axis)");
case (-2...2,-2...2):
print("(\(point.0),\(point.1)) is inside the box");
default:
print("(\(point.0),\(point.1)) is outside of the box");
}
let point2 = (0,2);
switch point2 {
case (let x,0):
print("on the x-axis with an x value of \(x)");
case (0, let y):
print("on the y-axis with a y value of \(y)");
case (let x, let y):
print("somewhere else at (\(x),\(y))");
}
//where
let point3 = (1,-1);
switch point3 {
case let (x,y) where x == y:
print("(\(x),\(y)) is on the line x == y");
case let (x, y) where x == -y:
print("(\(x),\(y)) is on the line x == -y");
case let (x,y):
print("(\(x),\(y)) is just some arbitrarypoint");
}
//fallthrough
/**
如果需要C语言风格的贯穿特性,可以在每个需要该特性的case分支中使用fallthrough关键字
*/
let integerToDescibe = 5;
var description = "the number \(integerToDescibe) is";
switch integerToDescibe {
case 2,3,4,5,6,7,11,13,17,19:
description += "a prime number, and also";
// fallthrough
default:
description += " an integer";
}
print(description);
//带标签的语句
/**
通过该语句的关键词的同一行前面放置一个标签,并且该标签后面还需带着一个冒号。
`label name`: while `condition` {
`statements`
}
*/
let finalSquare = 25;
var board = Array<Int>(count: finalSquare + 1, repeatedValue: 0);
board[3] = 8;
board[6] = 11;
board[9] = 9;
board[10] = 2;
board[14] = -10;
board[19] = -11;
board[22] = -2;
board[24] = -8;
var square = 0;
var diceRoll = 0
gameLoop : while square != finalSquare {
if ++diceRoll == 7 {
diceRoll = 1;
}
switch square + diceRoll {
case finalSquare:
print("到达最后一个方块,游戏结束");
break gameLoop;
case let newSquare where newSquare > finalSquare:
print("超出最后一个方块,再掷一次");
continue gameLoop;
default:
print("本次移动有效");
square += diceRoll;
square += board[square];
}
}
print("Game over!");