欠如

来世は貝になりたい

Swiftの文法について復習してみるControl Flow

前回に引き続きツアーをやりますね・・・

今回はControl Flow(制御の流れ)がテーマになります。

Control Flow

Use if and switch to make conditionals, and use for-in, while, and repeat-while to make loops. Parentheses around the condition or loop variable are optional. Braces around the body are required.

ifとswitchを使用して条件を作成し、for-in、while、およびrepeat-whileを使用してループを作成します。 条件変数またはループ変数の前後のかっこはオプションです。 身体の周りに括弧が必要です。

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}
print(teamScore)

実行結果は下記となります

Linking ./.build/x86_64-unknown-linux/debug/TempCode
11
In an if statement, the conditional must be a Boolean expression—this means that code such as if score { ... } is an error, not an implicit comparison to zero.

ifステートメントでは、条件式はブール式でなければなりません。つまり、score {...}がエラーであり、ゼロとの暗黙の比較ではありません。
You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that a value is missing. Write a question mark (?) after the type of a value to mark the value as optional.

ifとletを使って、欠けているかもしれない値を扱うことができます。 これらの値はオプションとして表されます。 オプションの値には値が含まれているか、値がないことを示すnilが含まれています。 値の型の後に疑問符(?)を書き、値をオプションとしてマークします。
var optionalString: String? = "Hello"
print(optionalString == nil)
 
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
}

上記コードを実行すれば以下の通りになります

Linking ./.build/x86_64-unknown-linux/debug/TempCode
false
Hello, John Appleseed
If the optional value is nil, the conditional is false and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant after let, which makes the unwrapped value available inside the block of code.

オプションの値がnilの場合、条件はfalseで、カッコ内のコードはスキップされます。 それ以外の場合は、オプションの値がラップされ、letの後に定数に代入されます。これにより、アンラップされた値がコードブロック内で使用可能になります。
Another way to handle optional values is to provide a default value using the ?? operator. If the optional value is missing, the default value is used instead.

オプションの値を処理するもう1つの方法は、??を使用してデフォルト値を指定することです。 オペレーター。 オプションの値がない場合は、代わりにデフォルト値が使用されます。
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"

実行すれば以下の通りになります

Linking ./.build/x86_64-unknown-linux/debug/TempCode
Hi John Appleseed
Switches support any kind of data and a wide variety of comparison operations—they aren’t limited to integers and tests for equality.

スイッチは、あらゆる種類のデータと多種多様な比較演算をサポートします。整数と同等性のテストに限定されません。
import Foundation
let vegetable = "red pepper"
switch vegetable {
case "celery":
    print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
    print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
    print("Is it a spicy \(x)?")
default:
    print("Everything tastes good in soup.")
}

hasSuffix:接尾が一致 => true

実行すれば以下の通りになります

Linking ./.build/x86_64-unknown-linux/debug/TempCode
Is it a spicy red pepper?
Notice how let can be used in a pattern to assign the value that matched the pattern to a constant.

After executing the code inside the switch case that matched, the program exits from the switch statement. Execution doesn’t continue to the next case, so there is no need to explicitly break out of the switch at the end of each case’s code.

You use for-in to iterate over items in a dictionary by providing a pair of names to use for each key-value pair. Dictionaries are an unordered collection, so their keys and values are iterated over in an arbitrary order.

どのパターンがパターンに使用され、パターンに一致する値を定数に割り当てるかに注目してください。

一致したスイッチケース内のコードを実行した後、プログラムはswitch文を終了します。 実行は次のケースに進むことはないので、各ケースのコードの終わりにスイッチから明示的に抜け出す必要はありません。

for-inを使用して、各キーと値のペアに使用する名前のペアを提供することによって、ディクショナリ内の項目を反復処理します。 辞書は並べ替えられていないコレクションなので、キーと値は任意の順序で反復されます。
let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
print(largest)

実行すれば以下の通りになります

/swift-execution/Sources/main.swift:7:6: warning: immutable value 'kind' was never used; consider replacing with '_' or removing it
for (kind, numbers) in interestingNumbers {
     ^~~~
     _
Linking ./.build/x86_64-unknown-linux/debug/TempCode
25

numbersで配列を取得しその後numberで配列内のデータを一件ずつ取得しています

Use while to repeat a block of code until a condition changes. The condition of a loop can be at the end instead, ensuring that the loop is run at least once.

whileを使用して、条件が変わるまでコードブロックを繰り返します。 代わりにループの状態を最後に置いて、ループが少なくとも1回実行されるようにすることができます。
var n = 2
while n < 100 {
    n *= 2
}
print(n)
 
var m = 2
repeat {
    m *= 2
} while m < 100
print(m)

下記が実行結果となります

Linking ./.build/x86_64-unknown-linux/debug/TempCode
128
128
You can keep an index in a loop by using ..< to make a range of indexes.

インデックスの範囲を作成するには、.. <を使用してループ内のインデックスを保持することができます。
var total = 0
for i in 0..<4 {
    total += i
}
print(total)

下記が実行結果となります

Linking ./.build/x86_64-unknown-linux/debug/TempCode
6
Use ..< to make a range that omits its upper value, and use ... to make a range that includes both values.

.. <を使用して上限値を省略した範囲を作成し、...を使用して両方の値を含む範囲を作成します。

長くなりましたが今回は以上となります