SWIFT構文クリーンアップ#8


ソース:アップル公式SWIFTレポート

Repeat-While


SWIFTは、他の言語で使用されるdo-while構文をrepeat-while構文として提供します.動作方式は同じです.
var index = 5
let finalIndex = 5
repeat {
    print("Current Index: \(index)") // 5
} while index < finalIndex

Switch


If条件文は、SWIFTや他の言語に似ています.しかし、スイッチには多くの違いがあります.SWIFTのスイッチはほぼ同じですが、Implicit Fallthroughはありません.次の例
int i = 0
switch(i) {
case 0:
	cout << "i is 0\n";
default:
	cout << "i is not 0";
}
/*
 result: 
	 i is 0
	 i is not 0
 */
一般的にbreakがない場合、スイッチのcaseは上記のコードのすべての条件コードを実行します.これは下に落ちたようでSWIFTでFallthroughと呼ばれています
スイッチドアを使用する場合は、ケースごとに割り込みを1回使用するのが面倒です.ただし、SWIFTでは、breakがなくても対応するcaseのみを実行し、スイッチを終了する(逆に、SWIFTは既存のスイッチと同じキーワードfallroughを提供する)!
let i = 0
switch(i) {
case 0:
	print("i is 0\n");
//  fallthrough
default:
	print("i is not 0");
}
/*
 result: 
	 i is 0
 */
またcaseの条件下では,他の言語よりも多様な形式の条件文を追加することができる.次の例です.
let approximateCount = 62
let natualCount: String
switch approximateCount {
case 0:
    natualCount = "no"
case 1..<5:
    natualCount = "a few"
case 5..<12:
    natualCount = "several"
default:
    natualCount = "many"
}
print(natualCount) // many
上記の例のように、条件にRangeを入れることもできます.また、case文内で付与値を取得することもできます.SWIFTはこれをValue Bindingと解釈する.
let anotherPoint = (2, 0)
switch anotherPoint {
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 an y value of \(y)")
case let (x, y):
    print("somewhere else at (\(x), \(y))")
}
また、case内で割り当てられた値を使用して新しい条件を作成することもできます.
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
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 arbitrary point")
}
今までSWIFTを勉強しているうちに、Switchの文法が一番好きです.C++では、breakを1つずつ書くのも面倒で、判断できる資料型も少ないので、一般的にはSWIFTで多く使われるはずです.