ステートメント(声明)
日本語を消す 英語を消す下記URLから引用し、日本語訳をつけてみました
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/statements
Group expressions and control the flow of execution.
式をグループ化し、実行フローを制御します。
In Swift, there are three kinds of statements: simple statements, compiler control statements, and control flow statements. Simple statements are the most common and consist of either an expression or a declaration. Compiler control statements allow the program to change aspects of the compiler’s behavior and include a conditional compilation block and a line control statement.
Swift には、単純なステートメント、コンパイラ制御ステートメント、および制御フロー ステートメントの 3 種類のステートメントがあります。 単純なステートメントが最も一般的であり、式または宣言のいずれかで構成されます。 コンパイラー制御ステートメントを使用すると、プログラムはコンパイラーの動作の側面を変更し、条件付きコンパイル ブロックと行制御ステートメントを含めることができます。
Control flow statements are used to control the flow of execution in a program. There are several types of control flow statements in Swift, including loop statements, branch statements, and control transfer statements. Loop statements allow a block of code to be executed repeatedly, branch statements allow a certain block of code to be executed only when certain conditions are met, and control transfer statements provide a way to alter the order in which code is executed. In addition, Swift provides a do statement to introduce scope, and catch and handle errors, and a defer statement for running cleanup actions just before the current scope exits.
制御フロー ステートメントは、プログラムの実行フローを制御するために使用されます。 Swift には、ループ ステートメント、分岐ステートメント、制御転送ステートメントなど、いくつかの種類の制御フロー ステートメントがあります。 ループ ステートメントを使用すると、コードのブロックを繰り返し実行できます。分岐ステートメントを使用すると、特定の条件が満たされた場合にのみ特定のコード ブロックを実行できます。また、制御転送ステートメントは、コードの実行順序を変更する方法を提供します。 さらに、Swift は、スコープを導入し、エラーをキャッチして処理するための do ステートメントと、現在のスコープが終了する直前にクリーンアップ アクションを実行するための defer ステートメントを提供します。
A semicolon (;) can optionally appear after any statement and is used to separate multiple statements if they appear on the same line.
セミコロン (;) は任意でステートメントの後に使用でき、複数のステートメントが同じ行にある場合にそれらを区切るために使用されます。
Grammar of a statement
statement → expression ;?
statement → declaration ;?
statement → loop-statement ;?
statement → branch-statement ;?
statement → labeled-statement ;?
statement → control-transfer-statement ;?
statement → defer-statement ;?
statement → do-statement ;?
statement → compiler-control-statement
statements → statement statements?
Loop Statements
ループステートメント
Loop statements allow a block of code to be executed repeatedly, depending on the conditions specified in the loop. Swift has three loop statements: a for–in statement, a while statement, and a repeat–while statement.
ループ ステートメントを使用すると、ループ内で指定された条件に応じてコード ブロックを繰り返し実行できます。 Swift には、for-in ステートメント、while ステートメント、repeat-while ステートメントの 3 つのループ ステートメントがあります。
Control flow in a loop statement can be changed by a break statement and a continue statement and is discussed in Break Statement and Continue Statement below.
ループ ステートメントの制御フローは、break ステートメントと continue ステートメントによって変更できます。これについては、以下の Break ステートメントと Continue ステートメントで説明します。
Grammar of a loop statement
loop-statement → for-in-statement
loop-statement → while-statement
loop-statement → repeat-while-statement
For-In Statement
For-Inステートメント
A for–in statement allows a block of code to be executed once for each item in a collection (or any type) that conforms to the Sequence(Link:developer.apple.com) protocol.
for-in ステートメントを使用すると、Sequence (Link:developer.apple.com)(英語)プロトコルに準拠するコレクション(または任意のタイプ)内のアイテムごとにコード ブロックを 1 回実行できます。
A for–in statement has the following form:
for-in ステートメントの形式は次のとおりです。
for <#item#> in <#collection#> {
<#statements#>
}
The makeIterator() method is called on the collection expression to obtain a value of an iterator type — that is, a type that conforms to the IteratorProtocol(Link:developer.apple.com) protocol. The program begins executing a loop by calling the next() method on the iterator. If the value returned isn’t nil, it’s assigned to the item pattern, the program executes the statements, and then continues execution at the beginning of the loop. Otherwise, the program doesn’t perform assignment or execute the statements, and it’s finished executing the for–in statement.
makeIterator() メソッドはコレクション式で呼び出され、イテレータ型、つまり IteratorProtocol(Link:developer.apple.com)(英語) プロトコルに準拠する型の値を取得します。 プログラムはイテレータで next() メソッドを呼び出すことでループの実行を開始します。 返された値が nil でない場合、その値は項目パターンに割り当てられ、プログラムはステートメントを実行し、ループの開始時に実行を継続します。 それ以外の場合、プログラムは代入やステートメントの実行を行わず、for-in ステートメントの実行を終了します。
Grammar of a for-in statement
for-in-statement → for case? pattern in expression where-clause? code-block
While Statement
Whileステートメント
A while statement allows a block of code to be executed repeatedly, as long as a condition remains true.
while ステートメントを使用すると、条件が true である限り、コードのブロックを繰り返し実行できます。
A while statement has the following form:
while ステートメントの形式は次のとおりです。
while <#condition#> {
<#statements#>
}
A while statement is executed as follows:
while ステートメントは次のように実行されます。
- The condition is evaluated.If
true, execution continues to step 2. Iffalse, the program is finished executing thewhilestatement. - 条件が評価されます。
trueの場合、実行はステップ 2 に進みます。falseの場合、プログラムはwhileステートメントの実行を終了します。 - The program executes the statements, and execution returns to step 1.
- プログラムはステートメントを実行し、ステップ 1 に戻ります。
Because the value of the condition is evaluated before the statements are executed, the statements in a while statement can be executed zero or more times.
条件の値はステートメントが実行される前に評価されるため、while ステートメント内のステートメントは 0 回以上実行される可能性があります。
The value of the condition must be of type Bool or a type bridged to Bool. The condition can also be an optional binding declaration, as discussed in Optional Binding.
条件の値は、Bool 型、または Bool にブリッジされた型である必要があります。 「オプションのバインディング」で説明されているように、条件はオプションのバインディング宣言にすることもできます。
Grammar of a while statement
while-statement → while condition-list code-block
condition-list → condition | condition , condition-list
condition → expression | availability-condition | case-condition | optional-binding-condition
case-condition → case pattern initializer
optional-binding-condition → let pattern initializer? | var pattern initializer?
Repeat-While Statement
Repeat-Whileステートメント
A repeat–while statement allows a block of code to be executed one or more times, as long as a condition remains true.
repeat-while ステートメントを使用すると、条件が true である限り、コードのブロックを 1 回以上実行できます。
A repeat–while statement has the following form:
repeat-while ステートメントは次の形式になります。
repeat {
<#statements#>
} while <#condition#>
A repeat–while statement is executed as follows:
repeat-while ステートメントは次のように実行されます。
- The program executes the statements, and execution continues to step 2.
- プログラムはステートメントを実行し、実行はステップ 2 に進みます。
- The condition is evaluated.If
true, execution returns to step 1. Iffalse, the program is finished executing therepeat–whilestatement. - 条件が評価されます。
trueの場合、実行はステップ 1 に戻ります。falseの場合、プログラムはrepeat-whileステートメントの実行を終了します。
Because the value of the condition is evaluated after the statements are executed, the statements in a repeat–while statement are executed at least once.
条件の値はステートメントの実行後に評価されるため、repeat-while ステートメント内のステートメントは少なくとも 1 回実行されます。
The value of the condition must be of type Bool or a type bridged to Bool.
条件の値は、Bool 型、または Bool にブリッジされた型である必要があります。
Grammar of a repeat-while statement
repeat-while-statement → repeat code-block while expression
Branch Statements
ブランチステートメント
Branch statements allow the program to execute certain parts of code depending on the value of one or more conditions. The values of the conditions specified in a branch statement control how the program branches and, therefore, what block of code is executed. Swift has three branch statements: an if statement, a guard statement, and a switch statement.
分岐ステートメントを使用すると、プログラムは 1 つ以上の条件の値に応じてコードの特定の部分を実行できます。 分岐ステートメントで指定された条件の値は、プログラムの分岐方法、つまりどのコード ブロックが実行されるかを制御します。 Swift には、if ステートメント、guard ステートメント、switch ステートメントの 3 つの分岐ステートメントがあります。
Control flow in an if statement or a switch statement can be changed by a break statement and is discussed in Break Statement below.
if ステートメントまたは switch ステートメントの制御フローは、break ステートメントによって変更できます。これについては、以下の Break ステートメントで説明します。
Grammar of a branch statement
branch-statement → if-statement
branch-statement → guard-statement
branch-statement → switch-statement
If Statement
イフステートメント
An if statement is used for executing code based on the evaluation of one or more conditions.
if ステートメントは、1 つ以上の条件の評価に基づいてコードを実行するために使用されます。
There are two basic forms of an if statement. In each form, the opening and closing braces are required.
if ステートメントには 2 つの基本的な形式があります。 各形式では、左中括弧と右中括弧が必要です。
The first form allows code to be executed only when a condition is true and has the following form:
最初の形式では、条件が true の場合にのみコードを実行でき、次の形式になります。
if <#condition#> {
<#statements#>
}
The second form of an if statement provides an additional else clause (introduced by the else keyword) and is used for executing one part of code when the condition is true and another part of code when the same condition is false. When a single else clause is present, an if statement has the following form:
if ステートメントの 2 番目の形式は、追加の else 句(else キーワードによって導入)を提供し、条件が true の場合はコードの一部を実行し、同じ条件が false の場合はコードの別の部分を実行するために使用されます。 単一の else 節が存在する場合、if ステートメントは次の形式になります。
if <#condition#> {
<#statements to execute if condition is true#>
} else {
<#statements to execute if condition is false#>
}
The else clause of an if statement can contain another if statement to test more than one condition. An if statement chained together in this way has the following form:
if ステートメントの else 節には、複数の条件をテストするための別の if ステートメントを含めることができます。 この方法で連結された if ステートメントは次の形式になります。
if <#condition 1#> {
<#statements to execute if condition 1 is true#>
} else if <#condition 2#> {
<#statements to execute if condition 2 is true#>
} else {
<#statements to execute if both conditions are false#>
}
The value of any condition in an if statement must be of type Bool or a type bridged to Bool. The condition can also be an optional binding declaration, as discussed in Optional Binding.
if ステートメント内の条件の値は、Bool 型、または Bool にブリッジされた型である必要があります。 「オプションのバインディング」で説明されているように、条件はオプションのバインディング宣言にすることもできます。
Grammar of an if statement
if-statement → if condition-list code-block else-clause?
else-clause → else code-block | else if-statement
Guard Statement
ガードステートメント
A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.
guard ステートメントは、1 つ以上の条件が満たされない場合にプログラム制御をスコープ外に移すために使用されます。
A guard statement has the following form:
guard ステートメントの形式は次のとおりです。
guard <#condition#> else {
<#statements#>
}
The value of any condition in a guard statement must be of type Bool or a type bridged to Bool. The condition can also be an optional binding declaration, as discussed in Optional Binding.
guard ステートメント内の条件の値は、Bool 型、または Bool にブリッジされた型である必要があります。 「オプションのバインディング」で説明されているように、条件はオプションのバインディング宣言にすることもできます。
Any constants or variables assigned a value from an optional binding declaration in a guard statement condition can be used for the rest of the guard statement’s enclosing scope.
guard ステートメント条件内のオプションのバインディング宣言から値が割り当てられた定数または変数は、ガード ステートメントを囲むスコープの残りの部分に使用できます。
The else clause of a guard statement is required, and must either call a function with the Never return type or transfer program control outside the guard statement’s enclosing scope using one of the following statements:
guard ステートメントの else 節は必須であり、Never return 型で関数を呼び出すか、次のいずれかのステートメントを使用してガード ステートメントを囲むスコープの外にプログラム制御を転送する必要があります。
returnbreakcontinuethrow
Control transfer statements are discussed in Control Transfer Statements below. For more information on functions with the Never return type, see Functions that Never Return.
コントロール転送ステートメントについては、以下のコントロール転送ステートメントで説明します。 Never return 型の関数の詳細については、「Return しない関数」を参照してください。
Grammar of a guard statement
guard-statement → guard condition-list else code-block
Switch Statement
スウィッチステートメント
A switch statement allows certain blocks of code to be executed depending on the value of a control expression.
switch ステートメントを使用すると、制御式の値に応じてコードの特定のブロックを実行できます。
A switch statement has the following form:
switch ステートメントの形式は次のとおりです。
switch <#control expression#> {
case <#pattern 1#>:
<#statements#>
case <#pattern 2#> where <#condition#>:
<#statements#>
case <#pattern 3#> where <#condition#>,
<#pattern 4#> where <#condition#>:
<#statements#>
default:
<#statements#>
}
The control expression of the switch statement is evaluated and then compared with the patterns specified in each case. If a match is found, the program executes the statements listed within the scope of that case. The scope of each case can’t be empty. As a result, you must include at least one statement following the colon (:) of each case label. Use a single break statement if you don’t intend to execute any code in the body of a matched case.
switch ステートメントの制御式が評価され、それぞれの場合に指定されたパターンと比較されます。 一致するものが見つかった場合、プログラムはそのケースの範囲内でリストされているステートメントを実行します。 各ケースのスコープを空にすることはできません。 したがって、各 case ラベルのコロン (:) の後に少なくとも 1 つのステートメントを含める必要があります。 一致したケースの本文でコードを実行する予定がない場合は、単一の Break ステートメントを使用します。
The values of expressions your code can branch on are very flexible. For example, in addition to the values of scalar types, such as integers and characters, your code can branch on the values of any type, including floating-point numbers, strings, tuples, instances of custom classes, and optionals. The value of the control expression can even be matched to the value of a case in an enumeration and checked for inclusion in a specified range of values. For examples of how to use these various types of values in switch statements, see Switch in Control Flow.
コードが分岐できる式の値は非常に柔軟です。 たとえば、整数や文字などのスカラー型の値に加えて、コードは浮動小数点数、文字列、タプル、カスタム クラスのインスタンス、オプションなどの任意の型の値に基づいて分岐できます。 コントロール式の値は、列挙内のケースの値と照合し、指定された値の範囲に含まれるかどうかをチェックすることもできます。 switch ステートメントでこれらのさまざまなタイプの値を使用する方法の例については、「制御フローの Switch」を参照してください。
A switch case can optionally contain a where clause after each pattern. A where clause is introduced by the where keyword followed by an expression, and is used to provide an additional condition before a pattern in a case is considered matched to the control expression. If a where clause is present, the statements within the relevant case are executed only if the value of the control expression matches one of the patterns of the case and the expression of the where clause evaluates to true. For example, a control expression matches the case in the example below only if it’s a tuple that contains two elements of the same value, such as (1, 1).
スイッチケースには、各パターンの後にオプションで where 句を含めることができます。 where 句は、where キーワードとそれに続く式によって導入され、ケース内のパターンが制御式に一致するとみなされる前に追加の条件を提供するために使用されます。 where 句が存在する場合、制御式の値がケースのパターンの 1 つと一致し、where 句の式が true と評価される場合にのみ、関連する case 内のステートメントが実行されます。 たとえば、制御式は、以下の例の(1, 1) など、同じ値の 2 つの要素を含むタプルである場合にのみ、一致します。
case let (x, y) where x == y:
As the above example shows, patterns in a case can also bind constants using the let keyword (they can also bind variables using the var keyword). These constants (or variables) can then be referenced in a corresponding where clause and throughout the rest of the code within the scope of the case. If the case contains multiple patterns that match the control expression, all of the patterns must contain the same constant or variable bindings, and each bound variable or constant must have the same type in all of the case’s patterns.
上の例が示すように、ケース内のパターンは let キーワードを使用して定数をバインドすることもできます(var キーワードを使用して変数をバインドすることもできます)。 これらの定数(または変数)は、対応する where 句内およびケースの範囲内のコードの残りの部分全体で参照できます。 ケースに制御式と一致する複数のパターンが含まれている場合、すべてのパターンに同じ定数または変数バインディングが含まれている必要があり、各バインドされた変数または定数はケースのすべてのパターンで同じ型である必要があります。
A switch statement can also include a default case, introduced by the default keyword. The code within a default case is executed only if no other cases match the control expression. A switch statement can include only one default case, which must appear at the end of the switch statement.
switch ステートメントには、default キーワードによって導入されるデフォルトのケースを含めることもできます。 デフォルトのケース内のコードは、他のケースが制御式と一致しない場合にのみ実行されます。 switch ステートメントにはデフォルト ケースを 1 つだけ含めることができ、これは switch ステートメントの最後に指定する必要があります。
Although the actual execution order of pattern-matching operations, and in particular the evaluation order of patterns in cases, is unspecified, pattern matching in a switch statement behaves as if the evaluation is performed in source order — that is, the order in which they appear in source code. As a result, if multiple cases contain patterns that evaluate to the same value, and thus can match the value of the control expression, the program executes only the code within the first matching case in source order.
パターン マッチング操作の実際の実行順序、特にケースのパターンの評価順序は指定されていませんが、switch ステートメント内のパターン マッチングは、評価がソースの順序、つまり、ソースコード内での出現順序で実行されるかのように動作します。その結果、複数のケースに同じ値に評価されるパターンが含まれており、制御式の値と一致する可能性がある場合、プログラムはソース順で最初に一致したケース内のコードのみを実行します。
Switch Statements Must Be Exhaustive
Switch ステートメントはすべてを網羅する必要があります
In Swift, every possible value of the control expression’s type must match the value of at least one pattern of a case. When this simply isn’t feasible (for example, when the control expression’s type is Int), you can include a default case to satisfy the requirement.
Swift では、コントロール式の型のすべての可能な値が、ケースの少なくとも 1 つのパターンの値と一致する必要があります。 これが単純に不可能な場合(たとえば、コントロール式の型が Int の場合)、要件を満たすためにデフォルトのケースを含めることができます。
Switching Over Future Enumeration Cases
今後の列挙ケースの切り替え
A nonfrozen enumeration is a special kind of enumeration that may gain new enumeration cases in the future — even after you compile and ship an app. Switching over a nonfrozen enumeration requires extra consideration. When a library’s authors mark an enumeration as nonfrozen, they reserve the right to add new enumeration cases, and any code that interacts with that enumeration must be able to handle those future cases without being recompiled. Code that’s compiled in library evolution mode, code in the Swift standard library, Swift overlays for Apple frameworks, and C and Objective-C code can declare nonfrozen enumerations. For information about frozen and nonfrozen enumerations, see frozen.
非凍結列挙は、アプリをコンパイルして出荷した後でも、将来的に新しい列挙ケースが追加される可能性がある特別な種類の列挙です。 凍結されていない列挙を切り替えるには、特別な考慮が必要です。 ライブラリの作成者が列挙型を非凍結としてマークすると、新しい列挙型ケースを追加する権利を留保します。また、その列挙型を操作するコードは、再コンパイルせずに将来の列挙型ケースを処理できる必要があります。 ライブラリ進化モードでコンパイルされたコード、Swift 標準ライブラリのコード、Apple フレームワーク用の Swift オーバーレイ、および C および Objective-C コードは、凍結されていない列挙を宣言できます。 凍結列挙と非凍結列挙の詳細については、「凍結」をご覧ください。
When switching over a nonfrozen enumeration value, you always need to include a default case, even if every case of the enumeration already has a corresponding switch case. You can apply the @unknown attribute to the default case, which indicates that the default case should match only enumeration cases that are added in the future. Swift produces a warning if the default case matches any enumeration case that’s known at compiler time. This future warning informs you that the library author added a new case to the enumeration that doesn’t have a corresponding switch case.
非凍結列挙値を切り替えるときは、列挙のすべてのケースに対応するスイッチ ケースがすでに存在する場合でも、常にデフォルトのケースを含める必要があります。 @unknown 属性をデフォルトのケースに適用できます。これは、デフォルトのケースが将来追加される列挙ケースのみと一致する必要があることを示します。 デフォルトのケースがコンパイル時に既知の列挙型のケースと一致する場合、Swift は警告を生成します。 この将来の警告は、ライブラリの作成者が対応するスイッチ ケースを持たない新しいケースを列挙に追加したことを通知します。
The following example switches over all three existing cases of the Swift standard library’s Mirror.AncestorRepresentation(Link:developer.apple.com) enumeration. If you add additional cases in the future, the compiler generates a warning to indicate that you need to update the switch statement to take the new cases into account.
次の例では、Swift 標準ライブラリの Mirror.AncestorRepresentation(Link:developer.apple.com)(英語) 列挙の 3 つの既存のケースをすべて切り替えます。 今後さらにケースを追加すると、コンパイラは、新しいケースを考慮に入れるために switch ステートメントを更新する必要があることを示す警告を生成します。
let representation: Mirror.AncestorRepresentation = .generated
switch representation {
case .customized:
print("Use the nearest ancestor’s implementation.")
case .generated:
print("Generate a default mirror for all ancestor classes.")
case .suppressed:
print("Suppress the representation of all ancestor classes.")
@unknown default:
print("Use a representation that was unknown when this code was compiled.")
}
// Prints "Generate a default mirror for all ancestor classes."
Execution Does Not Fall Through Cases Implicitly
実行はケースを暗黙的に通過しない
After the code within a matched case has finished executing, the program exits from the switch statement. Program execution doesn’t continue or “fall through” to the next case or default case. That said, if you want execution to continue from one case to the next, explicitly include a fallthrough statement, which simply consists of the fallthrough keyword, in the case from which you want execution to continue. For more information about the fallthrough statement, see Fallthrough Statement below.
一致したケース内のコードの実行が完了すると、プログラムは switch ステートメントから終了します。 プログラムの実行が続行されないか、次のケースまたはデフォルトのケースに「フォールスルー」されます。 ただし、あるケースから次のケースに実行を継続したい場合は、実行を継続するケースに、fallthrough キーワードだけで構成されるfallthrough ステートメントを明示的に含めます。 fallthrough ステートメントの詳細については、以下のフォールスルー ステートメントをご覧ください。
Grammar of a switch statement
switch-statement → switch expression { switch-cases? }
switch-cases → switch-case switch-cases?
switch-case → case-label statements
switch-case → default-label statements
switch-case → conditional-switch-case
case-label → attributes? case case-item-list :
case-item-list → pattern where-clause? | pattern where-clause? , case-item-list
default-label → attributes? default :
where-clause → where where-expression
where-expression → expression
conditional-switch-case → switch-if-directive-clause switch-elseif-directive-clauses? switch-else-directive-clause? endif-directive
switch-if-directive-clause → if-directive compilation-condition switch-cases?
switch-elseif-directive-clauses → elseif-directive-clause switch-elseif-directive-clauses?
switch-elseif-directive-clause → elseif-directive compilation-condition switch-cases?
switch-else-directive-clause → else-directive switch-cases?
Labeled Statement
ラベル付きステートメント
You can prefix a loop statement, an if statement, a switch statement, or a do statement with a statement label, which consists of the name of the label followed immediately by a colon (:). Use statement labels with break and continue statements to be explicit about how you want to change control flow in a loop statement or a switch statement, as discussed in Break Statement and Continue Statement below.
ループ ステートメント、if ステートメント、switch ステートメント、または do ステートメントの前にステートメント ラベルを付けることができます。ステートメント ラベルは、ラベルの名前の直後にコロン (:) が続きます。 以下の Break ステートメントとContinue ステートメントで説明するように、ループ ステートメントまたは switch ステートメントの制御フローを変更する方法を明示するには、break ステートメントと continue ステートメントを含むステートメント ラベルを使用します。
The scope of a labeled statement is the entire statement following the statement label. You can nest labeled statements, but the name of each statement label must be unique.
ラベル付きステートメントのスコープは、ステートメント ラベルに続くステートメント全体です。 ラベル付きステートメントをネストできますが、各ステートメント ラベルの名前は一意である必要があります。
For more information and to see examples of how to use statement labels, see Labeled Statements in Control Flow.
詳細とステートメント ラベルの使用例については、「制御フローのラベル付きステートメント」を参照してください。
Grammar of a labeled statement
labeled-statement → statement-label loop-statement
labeled-statement → statement-label if-statement
labeled-statement → statement-label switch-statement
labeled-statement → statement-label do-statement
statement-label → label-name :
label-name → identifier
Control Transfer Statements
制御転送ステートメント
Control transfer statements can change the order in which code in your program is executed by unconditionally transferring program control from one piece of code to another. Swift has five control transfer statements: a break statement, a continue statement, a fallthrough statement, a return statement, and a throw statement.
制御転送ステートメントは、プログラム制御をあるコードから別のコードに無条件に転送することにより、プログラム内のコードが実行される順序を変更できます。 Swift には、break ステートメント、 continue ステートメント、fallthrough ステートメント、return ステートメント、throw ステートメントの 5 つの制御転送ステートメントがあります。
Grammar of a control transfer statement
control-transfer-statement → break-statement
control-transfer-statement → continue-statement
control-transfer-statement → fallthrough-statement
control-transfer-statement → return-statement
control-transfer-statement → throw-statement
Break Statement
ブレークステートメント
A break statement ends program execution of a loop, an if statement, or a switch statement. A break statement can consist of only the break keyword, or it can consist of the break keyword followed by the name of a statement label, as shown below.
break ステートメントは、ループ、if ステートメント、または switch ステートメントのプログラム実行を終了します。 break ステートメントは、break キーワードのみで構成することも、以下に示すように、break キーワードとその後にステートメント ラベルの名前が続く構成にすることもできます。
break
break <#label name#>When a break statement is followed by the name of a statement label, it ends program execution of the loop, if statement, or switch statement named by that label.
break ステートメントの後にステートメント ラベルの名前が続くと、そのラベルで指定されたループ、if ステートメント、または switch ステートメントのプログラム実行が終了します。
When a break statement isn’t followed by the name of a statement label, it ends program execution of the switch statement or the innermost enclosing loop statement in which it occurs. You can’t use an unlabeled break statement to break out of an if statement.
break ステートメントの後にステートメント ラベルの名前が続かない場合、switch ステートメントまたはそれが発生する最も内側のループ ステートメントのプログラム実行が終了します。 ラベルのない break ステートメントを使用して if ステートメントから抜け出すことはできません。
In both cases, program control is then transferred to the first line of code following the enclosing loop or switch statement, if any.
どちらの場合も、プログラム制御は、それを囲んでいるループまたは switch ステートメント(存在する場合)に続くコードの最初の行に転送されます。
For examples of how to use a break statement, see Break and Labeled Statements in Control Flow.
break ステートメントの使用方法の例については、「制御フロー」の「Breakとラベル付きステートメント」を参照してください。
Grammar of a break statement
break-statement → break label-name?
Continue Statement
コンティニューステートメント
A continue statement ends program execution of the current iteration of a loop statement but doesn’t stop execution of the loop statement. A continue statement can consist of only the continue keyword, or it can consist of the continue keyword followed by the name of a statement label, as shown below.
continue ステートメントは、ループ ステートメントの現在の反復のプログラム実行を終了しますが、ループ ステートメントの実行は停止しません。 continue ステートメントは、 continue キーワードのみで構成することも、以下に示すように continue キーワードとその後に続くステートメント ラベルの名前で構成することもできます。
continue
continue <#label name#>
When a continue statement is followed by the name of a statement label, it ends program execution of the current iteration of the loop statement named by that label.
continue ステートメントの後にステートメント ラベルの名前が続くと、そのラベルで指定されたループ ステートメントの現在の反復のプログラム実行が終了します。
When a continue statement isn’t followed by the name of a statement label, it ends program execution of the current iteration of the innermost enclosing loop statement in which it occurs.
continue ステートメントの後にステートメント ラベルの名前が続かない場合、それが発生する最も内側のループ ステートメントの現在の反復のプログラム実行が終了します。
In both cases, program control is then transferred to the condition of the enclosing loop statement.
どちらの場合も、プログラム制御は、それを囲んでいるループ ステートメントの条件に移されます。
In a for statement, the increment expression is still evaluated after the continue statement is executed, because the increment expression is evaluated after the execution of the loop’s body.
for ステートメントでは、インクリメント式はループ本体の実行後に評価されるため、Continue ステートメントの実行後もインクリメント式が評価されます。
For examples of how to use a continue statement, see Continue and Labeled Statements in Control Flow.
continue ステートメントの使用方法の例については、制御フローの Continue とラベル付きステートメントを参照してください。
Grammar of a continue statement
continue-statement → continue label-name?
Fallthrough Statement
フォールスルーステートメント
A fallthrough statement consists of the fallthrough keyword and occurs only in a case block of a switch statement. A fallthrough statement causes program execution to continue from one case in a switch statement to the next case. Program execution continues to the next case even if the patterns of the case label don’t match the value of the switch statement’s control expression.
fallthrough ステートメントはfallthrough キーワードで構成され、switch ステートメントの case ブロック内でのみ使用されます。 fallthrough ステートメントにより、プログラムの実行が switch ステートメント内の 1 つのケースから次のケースに継続されます。 ケースラベルのパターンが switch ステートメントの制御式の値と一致しない場合でも、プログラムの実行は次のケースに続行されます。
A fallthrough statement can appear anywhere inside a switch statement, not just as the last statement of a case block, but it can’t be used in the final case block. It also can’t transfer control into a case block whose pattern contains value binding patterns.
fallthrough ステートメントは、case ブロックの最後のステートメントとしてだけでなく、switch ステートメント内のどこにでも使用できますが、最後の case ブロックでは使用できません。 また、パターンに値バインディング パターンが含まれる case ブロックに制御を移すこともできません。
For an example of how to use a fallthrough statement in a switch statement, see Control Transfer Statements in Control Flow.
switch ステートメントでfallthrough ステートメントを使用する方法の例については、制御フローの制御転送ステートメントを参照してください。
Grammar of a fallthrough statement
fallthrough-statement → fallthrough
Return Statement
リターンステートメント
A return statement occurs in the body of a function or method definition and causes program execution to return to the calling function or method. Program execution continues at the point immediately following the function or method call.
return ステートメントは関数またはメソッド定義の本体で発生し、プログラムの実行を呼び出し元の関数またはメソッドに戻します。 プログラムの実行は、関数またはメソッド呼び出しの直後から続行されます。
A return statement can consist of only the return keyword, or it can consist of the return keyword followed by an expression, as shown below.
return ステートメントは、return キーワードのみで構成することも、以下に示すように return キーワードとそれに続く式で構成することもできます。
return
return <#expression#>When a return statement is followed by an expression, the value of the expression is returned to the calling function or method. If the value of the expression doesn’t match the value of the return type declared in the function or method declaration, the expression’s value is converted to the return type before it’s returned to the calling function or method.
return ステートメントの後に式が続く場合、式の値が呼び出し元の関数またはメソッドに返されます。 式の値が関数またはメソッドの宣言で宣言された戻り値の型の値と一致しない場合、式の値は呼び出し元の関数またはメソッドに返される前に戻り値の型に変換されます。
Note
注釈
As described in Failable Initializers, a special form of the return statement (return nil) can be used in a failable initializer to indicate initialization failure.
「失敗可能なイニシャライザ」で説明されているように、特殊な形式の return ステートメント (return nil) をfailable イニシャライザで使用して、初期化の失敗を示すことができます。
When a return statement isn’t followed by an expression, it can be used only to return from a function or method that doesn’t return a value (that is, when the return type of the function or method is Void or ()).
return ステートメントの後に式が続かない場合、値を返さない関数またはメソッドから戻るためにのみ使用できます(つまり、関数またはメソッドの戻り値の型が Void または () の場合)。 。
Grammar of a return statement
return-statement → return expression?
Throw Statement
スローステートメント
A throw statement occurs in the body of a throwing function or method, or in the body of a closure expression whose type is marked with the throws keyword.
throw ステートメントは、スロー関数またはメソッドの本体、または型が throws キーワードでマークされているクロージャ式の本体で発生します。
A throw statement causes a program to end execution of the current scope and begin error propagation to its enclosing scope. The error that’s thrown continues to propagate until it’s handled by a catch clause of a do statement.
throw ステートメントにより、プログラムは現在のスコープの実行を終了し、それを囲んでいるスコープへのエラーの伝播を開始します。 スローされたエラーは、do ステートメントの catch 句によって処理されるまで伝播し続けます。
A throw statement consists of the throw keyword followed by an expression, as shown below.
throw ステートメントは、以下に示すように、throw キーワードとそれに続く式で構成されます。
throw <#expression#>
The value of the expression must have a type that conforms to the Error protocol.
式の値には、エラー プロトコルに準拠した型が必要です。
For an example of how to use a throw statement, see Propagating Errors Using Throwing Functions in Error Handling.
throw ステートメントの使用方法の例については、「エラー処理」の「スロー関数を使用したエラーの伝播」を参照してください。
Grammar of a throw statement
throw-statement → throw expression
Defer Statement
デファー(延期)ステートメント
A defer statement is used for executing code just before transferring program control outside of the scope that the defer statement appears in.
defer ステートメントは、defer ステートメントが含まれるスコープ外にプログラム制御を転送する直前にコードを実行するために使用されます。
A defer statement has the following form:
defer ステートメントの形式は次のとおりです。
defer {
<#statements#>
}
The statements within the defer statement are executed no matter how program control is transferred. This means that a defer statement can be used, for example, to perform manual resource management such as closing file descriptors, and to perform actions that need to happen even if an error is thrown.
defer ステートメント内のステートメントは、プログラム制御がどのように転送されたかに関係なく実行されます。 これは、defer ステートメントを使用して、ファイル記述子を閉じるなどの手動リソース管理を実行したり、エラーがスローされた場合でも実行する必要があるアクションを実行したりできることを意味します。
The statements in the defer statement are executed at the end of the scope that encloses the defer statement.
defer ステートメント内のステートメントは、defer ステートメントを囲むスコープの最後で実行されます。
func f(x: Int) {
defer { print("First defer") }
if x < 10 {
defer { print("Second defer") }
print("End of if")
}
print("End of function")
}
f(x: 5)
// Prints "End of if"
// Prints "Second defer"
// Prints "End of function"
// Prints "First defer"
In the code above, the defer in the if statement executes before the defer declared in the function f because the scope of the if statement ends before the scope of the function.
上記のコードでは、if ステートメントの defer は、関数 f で宣言された defer より前に実行されます。これは、if ステートメントのスコープが関数のスコープより前に終了するためです。
If multiple defer statements appear in the same scope, the order they appear is the reverse of the order they’re executed. Executing the last defer statement in a given scope first means that statements inside that last defer statement can refer to resources that will be cleaned up by other defer statements.
複数の defer ステートメントが同じスコープ内に出現する場合、出現する順序は実行される順序の逆になります。 指定されたスコープで最初に最後の defer ステートメントを実行すると、その最後の defer ステートメント内のステートメントは、他の defer ステートメントによってクリーンアップされるリソースを参照できることになります。
func f() {
defer { print("First defer") }
defer { print("Second defer") }
print("End of function")
}
f()
// Prints "End of function"
// Prints "Second defer"
// Prints "First defer"
The statements in the defer statement can’t transfer program control outside of the defer statement.
defer ステートメント内のステートメントは、defer ステートメントの外にプログラム制御を移すことはできません。
Grammar of a defer statement
defer-statement → defer code-block
Do Statement
ドゥステートメント
The do statement is used to introduce a new scope and can optionally contain one or more catch clauses, which contain patterns that match against defined error conditions. Variables and constants declared in the scope of a do statement can be accessed only within that scope.
do ステートメントは、新しいスコープを導入するために使用され、オプションで 1 つ以上の catch 句を含めることができます。この句には、定義されたエラー条件と一致するパターンが含まれます。 do ステートメントのスコープ内で宣言された変数と定数には、そのスコープ内でのみアクセスできます。
A do statement in Swift is similar to curly braces ({}) in C used to delimit a code block, and doesn’t incur a performance cost at runtime.
Swift の do ステートメントは、コード ブロックを区切るために使用される C の中括弧 ({}) に似ており、実行時にパフォーマンスのコストがかかりません。
A do statement has the following form:
do ステートメントの形式は次のとおりです。
do {
try <#expression#>
<#statements#>
} catch <#pattern 1#> {
<#statements#>
} catch <#pattern 2#> where <#condition#> {
<#statements#>
} catch <#pattern 3#>, <#pattern 4#> where <#condition#> {
<#statements#>
} catch {
<#statements#>
}
If any statement in the do code block throws an error, program control is transferred to the first catch clause whose pattern matches the error. If none of the clauses match, the error propagates to the surrounding scope. If an error is unhandled at the top level, program execution stops with a runtime error.
do コード ブロック内のステートメントのいずれかがエラーをスローした場合、プログラム制御は、パターンがエラーに一致する最初の catch 節に移されます。 どの句も一致しない場合、エラーは周囲のスコープに伝播します。 エラーがトップレベルで処理されない場合、プログラムの実行は実行時エラーで停止します。
Like a switch statement, the compiler attempts to infer whether catch clauses are exhaustive. If such a determination can be made, the error is considered handled. Otherwise, the error can propagate out of the containing scope, which means the error must be handled by an enclosing catch clause or the containing function must be declared with throws.
switch ステートメントと同様に、コンパイラは catch 句が完全であるかどうかを推論しようとします。 そのような決定ができる場合、エラーは処理されたとみなされます。 そうしないと、エラーが含まれるスコープの外に伝播する可能性があります。つまり、エラーを囲む catch 句で処理するか、含まれる関数を throw で宣言する必要があります。
A catch clause that has multiple patterns matches the error if any of its patterns match the error. If a catch clause contains multiple patterns, all of the patterns must contain the same constant or variable bindings, and each bound variable or constant must have the same type in all of the catch clause’s patterns.
複数のパターンを持つ catch 句は、いずれかのパターンがエラーと一致する場合にエラーと一致します。 catch 句に複数のパターンが含まれる場合、すべてのパターンに同じ定数または変数バインディングが含まれている必要があり、バインドされた各変数または定数は、catch 句のすべてのパターンで同じ型である必要があります。
To ensure that an error is handled, use a catch clause with a pattern that matches all errors, such as a wildcard pattern (_). If a catch clause doesn’t specify a pattern, the catch clause matches and binds any error to a local constant named error. For more information about the patterns you can use in a catch clause, see Patterns.
エラーが確実に処理されるようにするには、ワイルドカード パターン (_) など、すべてのエラーに一致するパターンを持つ catch 句を使用します。 catch 句でパターンが指定されていない場合、catch 句はエラーを照合し、error という名前のローカル定数にバインドします。 catch句で使用できるパターンの詳細については、「パターン」を参照してください。
To see an example of how to use a do statement with several catch clauses, see Handling Errors.
複数の catch 句を含む do ステートメントの使用例については、「エラーの処理」をご覧ください。
Grammar of a do statement
do-statement → do code-block catch-clauses?
catch-clauses → catch-clause catch-clauses?
catch-clause → catch catch-pattern-list? code-block
catch-pattern-list → catch-pattern | catch-pattern , catch-pattern-list
catch-pattern → pattern where-clause?
Compiler Control Statements
コンパイラ制御ステートメント
Compiler control statements allow the program to change aspects of the compiler’s behavior. Swift has three compiler control statements: a conditional compilation block a line control statement, and a compile-time diagnostic statement.
コンパイラ制御ステートメントを使用すると、プログラムはコンパイラの動作の側面を変更できます。 Swift には、条件付きコンパイル ブロック、行制御ステートメント、およびコンパイル時診断ステートメントの 3 つのコンパイラ制御ステートメントがあります。
Grammar of a compiler control statement
compiler-control-statement → conditional-compilation-block
compiler-control-statement → line-control-statement
compiler-control-statement → diagnostic-statement
Conditional Compilation Block
条件付きコンパイル ブロック
A conditional compilation block allows code to be conditionally compiled depending on the value of one or more compilation conditions.
条件付きコンパイル ブロックを使用すると、1 つ以上のコンパイル条件の値に応じてコードを条件付きでコンパイルできます。
Every conditional compilation block begins with the #if compilation directive and ends with the #endif compilation directive. A simple conditional compilation block has the following form:
すべての条件付きコンパイル ブロックは、#if コンパイル ディレクティブで始まり、#endif コンパイル ディレクティブで終わります。 単純な条件付きコンパイル ブロックは次の形式になります。
#if <#compilation condition#>
<#statements#>
#endif
Unlike the condition of an if statement, the compilation condition is evaluated at compile time. As a result, the statements are compiled and executed only if the compilation condition evaluates to true at compile time.
if ステートメントの条件とは異なり、コンパイル条件はコンパイル時に評価されます。 その結果、コンパイル時にコンパイル条件が true と評価された場合にのみ、ステートメントがコンパイルされ、実行されます。
The compilation condition can include the true and false Boolean literals, an identifier used with the -D command line flag, or any of the platform conditions listed in the table below.
コンパイル条件には、true と false のブール値リテラル、-D コマンド ライン フラグで使用される識別子、または以下の表にリストされているプラットフォーム条件のいずれかを含めることができます。
| Platform condition | Valid arguments |
|---|---|
os() | mac, i, watch, tv, vision, Linux, Windows |
arch() | i386, x86, arm, arm64 |
swift() | >= or < followed by a version number |
compiler() | >= or < followed by a version number |
can | A module name |
target | simulator, mac |
The version number for the swift() and compiler() platform conditions consists of a major number, optional minor number, optional patch number, and so on, with a dot (.) separating each part of the version number. There must not be whitespace between the comparison operator and the version number. The version for compiler() is the compiler version, regardless of the Swift version setting passed to the compiler. The version for swift() is the language version currently being compiled. For example, if you compile your code using the Swift 5 compiler in Swift 4.2 mode, the compiler version is 5 and the language version is 4.2. With those settings, the following code prints all three messages:
swift() および Compiler() プラットフォーム条件のバージョン番号は、メジャー番号、オプションのマイナー番号、オプションのパッチ番号などで構成され、バージョン番号の各部分はドット (.) で区切られます。 比較演算子とバージョン番号の間に空白を入れてはなりません。 Compiler() のバージョンは、コンパイラに渡される Swift バージョン設定に関係なく、コンパイラのバージョンです。 swift() のバージョンは、現在コンパイル中の言語バージョンです。 たとえば、Swift 5 コンパイラを Swift 4.2 モードで使用してコードをコンパイルする場合、コンパイラのバージョンは 5、言語バージョンは 4.2 になります。 これらの設定を使用すると、次のコードは 3 つのメッセージすべてを出力します。
#if compiler(>=5)
print("Compiled with the Swift 5 compiler or later")
#endif
#if swift(>=4.2)
print("Compiled in Swift 4.2 mode or later")
#endif
#if compiler(>=5) && swift(<5)
print("Compiled with the Swift 5 compiler or later in a Swift mode earlier than 5")
#endif
// Prints "Compiled with the Swift 5 compiler or later"
// Prints "Compiled in Swift 4.2 mode or later"
// Prints "Compiled with the Swift 5 compiler or later in a Swift mode earlier than 5"
The argument for the canImport() platform condition is the name of a module that may not be present on all platforms. The module can include periods (.) in its name. This condition tests whether it’s possible to import the module, but doesn’t actually import it. If the module is present, the platform condition returns true; otherwise, it returns false.
canImport() プラットフォーム条件の引数は、すべてのプラットフォームに存在するとは限らないモジュールの名前です。 モジュールの名前にはピリオド (.) を含めることができます。 この条件はモジュールをインポートできるかどうかをテストしますが、実際にはインポートしません。 モジュールが存在する場合、プラットフォーム条件は true を返します。 それ以外の場合は false を返します。
The targetEnvironment() platform condition returns true when code is being compiled for the specified environment; otherwise, it returns false.
targetEnvironment() プラットフォーム条件は、コードが指定された環境用にコンパイルされている場合に true を返します。 それ以外の場合は false を返します。
Note
注釈
The arch(arm) platform condition doesn’t return true for ARM 64 devices. The arch(i386) platform condition returns true when code is compiled for the 32–bit iOS simulator.
ARM 64 デバイスでは、arch(arm) プラットフォーム条件が true を返しません。 コードが 32 ビット iOS シミュレータ用にコンパイルされると、arch(i386) プラットフォーム条件は true を返します。
You can combine and negate compilation conditions using the logical operators &&, ||, and ! and use parentheses for grouping. These operators have the same associativity and precedence as the logical operators that are used to combine ordinary Boolean expressions.
論理演算子 &&、||、! を使用して、コンパイル条件を組み合わせたり、否定したりできます。 グループ化には括弧を使用します。 これらの演算子は、通常のブール式を結合するために使用される論理演算子と同じ結合性と優先順位を持ちます。
Similar to an if statement, you can add multiple conditional branches to test for different compilation conditions. You can add any number of additional branches using #elseif clauses. You can also add a final additional branch using an #else clause. Conditional compilation blocks that contain multiple branches have the following form:
if ステートメントと同様に、複数の条件分岐を追加して、さまざまなコンパイル条件をテストできます。 #elseif 句を使用して、任意の数のブランチを追加できます。 #else 句を使用して最後の追加ブランチを追加することもできます。 複数の分岐を含む条件付きコンパイル ブロックは次の形式になります。
#if <#compilation condition 1#>
<#statements to compile if compilation condition 1 is true#>
#elseif <#compilation condition 2#>
<#statements to compile if compilation condition 2 is true#>
#else
<#statements to compile if both compilation conditions are false#>
#endif
Note
注釈
Each statement in the body of a conditional compilation block is parsed even if it’s not compiled. However, there’s an exception if the compilation condition includes a swift() or compiler() platform condition: The statements are parsed only if the language or compiler version matches what is specified in the platform condition. This exception ensures that an older compiler doesn’t attempt to parse syntax introduced in a newer version of Swift.
条件付きコンパイル ブロックの本体内の各ステートメントは、コンパイルされていなくても解析されます。 ただし、コンパイル条件に swift() または Compiler() のプラットフォーム条件が含まれる場合は例外があります。ステートメントは、言語またはコンパイラーのバージョンがプラットフォーム条件で指定されたものと一致する場合にのみ解析されます。 この例外により、古いコンパイラーが新しいバージョンの Swift で導入された構文を解析しようとしなくなります。
For information about how you can wrap explicit member expressions in conditional compilation blocks, see Explicit Member Expression.
条件付きコンパイル ブロックで明示的なメンバー式をラップする方法については、「明示的なメンバー式」を参照してください。
Grammar of a conditional compilation block
conditional-compilation-block → if-directive-clause elseif-directive-clauses? else-directive-clause? endif-directive
if-directive-clause → if-directive compilation-condition statements?
elseif-directive-clauses → elseif-directive-clause elseif-directive-clauses?
elseif-directive-clause → elseif-directive compilation-condition statements?
else-directive-clause → else-directive statements?
if-directive → #if
elseif-directive → #elseif
else-directive → #else
endif-directive → #endif
compilation-condition → platform-condition
compilation-condition → identifier
compilation-condition → boolean-literal
compilation-condition → ( compilation-condition )
compilation-condition → ! compilation-condition
compilation-condition → compilation-condition && compilation-condition
compilation-condition → compilation-condition || compilation-condition
platform-condition → os ( operating-system )
platform-condition → arch ( architecture )
platform-condition → swift ( >= swift-version ) | swift ( < swift-version )
platform-condition → compiler ( >= swift-version ) | compiler ( < swift-version )
platform-condition → can ( import-path )
platform-condition → target ( environment )
operating-system → mac | i | watch | tv | Linux | Windows
architecture → i386 | x86 | arm | arm64
swift-version → decimal-digits swift-version-continuation?
swift-version-continuation → . decimal-digits swift-version-continuation?
environment → simulator | mac
Line Control Statement
行制御ステートメント
A line control statement is used to specify a line number and filename that can be different from the line number and filename of the source code being compiled. Use a line control statement to change the source code location used by Swift for diagnostic and debugging purposes.
行制御ステートメントは、コンパイルされるソース コードの行番号およびファイル名とは異なる行番号およびファイル名を指定するために使用されます。 行制御ステートメントを使用して、Swift が診断とデバッグの目的で使用するソース コードの場所を変更します。
A line control statement has the following forms:
行制御ステートメントの形式は次のとおりです。
#sourceLocation(file: <#file path#>, line: <#line number#>)
#sourceLocation()
The first form of a line control statement changes the values of the #line, #file, #fileID, and #filePath literal expressions, beginning with the line of code following the line control statement. The line number changes the value of #line, and is any integer literal greater than zero. The file path changes the value of #file, #fileID, and #filePath, and is a string literal. The specified string becomes the value of #filePath, and the last path component of the string is used by the value of #fileID. For information about #file, #fileID, and #filePath, see Literal Expression.
行制御ステートメントの最初の形式は、行制御ステートメントに続くコード行から始まる #line、#file、#fileID、#filePath リテラル式の値を変更します。 行番号は #line の値を変更し、ゼロより大きい任意の整数リテラルです。 ファイル パスは、#file、#fileID、#filePath の値を変更する文字列リテラルです。 指定された文字列は #filePath の値になり、文字列の最後のパス コンポーネントは #fileID の値によって使用されます。 #file、#fileID、#filePath については、「リテラル式」を参照してください。
The second form of a line control statement, #sourceLocation(), resets the source code location back to the default line numbering and file path.
行制御ステートメントの 2 番目の形式 #sourceLocation() は、ソース コードの場所をデフォルトの行番号とファイル パスにリセットします。
Grammar of a line control statement
line-control-statement → #source ( file: file-path , line: line-number )
line-control-statement → #source ( )
line-number → A decimal integer greater than zero
file-path → static-string-literal
Compile-Time Diagnostic Statement
コンパイル時の診断ステートメント
Prior to Swift 5.9, the #warning and #error statements emit a diagnostic during compilation. This behavior is now provided by the warning(_:)(Link:developer.apple.com) and error(_:)(Link:developer.apple.com) macros in the Swift standard library.
Swift 5.9 より前では、#warning ステートメントと #error ステートメントはコンパイル中に診断を生成します。 この動作は、Swift 標準ライブラリの warning(_:)(Link:developer.apple.com)(英語) マクロと error(_:)(Link:developer.apple.com)(英語) マクロによって提供されるようになりました。
Availability Condition
可用性条件
An availability condition is used as a condition of an if, while, and guard statement to query the availability of APIs at runtime, based on specified platforms arguments.
可用性条件は、指定されたプラットフォーム引数に基づいて実行時に API の可用性をクエリするための if、while、guard ステートメントの条件として使用されます。
An availability condition has the following form:
可用性条件は次の形式になります。
if #available(<#platform name#> <#version#>, <#...#>, *) {
<#statements to execute if the APIs are available#>
} else {
<#fallback statements to execute if the APIs are unavailable#>
}
You use an availability condition to execute a block of code, depending on whether the APIs you want to use are available at runtime. The compiler uses the information from the availability condition when it verifies that the APIs in that block of code are available.
使用する API が実行時に利用可能かどうかに応じて、可用性条件を使用してコード ブロックを実行します。 コンパイラは、そのコード ブロック内の API が利用可能であることを確認するときに、可用性条件からの情報を使用します。
The availability condition takes a comma-separated list of platform names and versions. Use iOS, macOS, watchOS, and tvOS for the platform names, and include the corresponding version numbers. The * argument is required and specifies that, on any other platform, the body of the code block guarded by the availability condition executes on the minimum deployment target specified by your target.
可用性条件には、プラットフォーム名とバージョンのカンマ区切りのリストが指定されます。 プラットフォーム名には iOS、macOS、watchOS、tvOS を使用し、対応するバージョン番号を含めます。 * 引数は必須であり、他のプラットフォームでは、可用性条件によって保護されたコード ブロックの本体が、ターゲットによって指定された最小のデプロイメント ターゲットで実行されることを指定します。
Unlike Boolean conditions, you can’t combine availability conditions using logical operators like && and ||. Instead of using ! to negate an availability condition, use an unavailability condition, which has the following form:
ブール条件とは異なり、&& や || などの論理演算子を使用して可用性条件を組み合わせることができません。 !を使い 可用性条件を無効にする代わりに、次の形式の非可用性条件を使用します。
if #unavailable(<#platform name#> <#version#>, <#...#>) {
<#fallback statements to execute if the APIs are unavailable#>
} else {
<#statements to execute if the APIs are available#>
}
The #unavailable form is syntactic sugar that negates the condition. In an unavailability condition, the * argument is implicit and must not be included. It has the same meaning as the * argument in an availability condition.
#unavailable 形式は、条件を否定する糖衣構文です。 利用不可能な状況では、* 引数は暗黙的であり、含めることはできません。 これは、可用性条件の * 引数と同じ意味を持ちます。
Grammar of an availability condition
availability-condition → #available ( availability-arguments )
availability-condition → #unavailable ( availability-arguments )
availability-arguments → availability-argument | availability-argument , availability-arguments
availability-argument → platform-name platform-version
availability-argument → *
platform-name → i | i
platform-name → mac | mac
platform-name → mac | mac
platform-name → watch | watch
platform-name → tv | tv
platform-name → vision
platform-version → decimal-digits
platform-version → decimal-digits . decimal-digits
platform-version → decimal-digits . decimal-digits . decimal-digits
