Swift には、値の範囲を表現する簡単な方法として、2 つの範囲演算子があります。
閉 (closed) 範囲演算子
閉範囲演算子 (a...b
) は、a
から b
までの範囲を定義し、値 a
と b
を含みます。a
の値を b
より大きくすることはできません。
閉範囲演算子は、for
–in
ループのように、すべての値を順に使用していくときに効果的です。
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
for
–in
ループについての詳しい情報は、Control Flow をご確認ください。
半開 (half-open) 範囲演算子
半開範囲演算子 (a..<b
) は、a
から b
までの範囲を定義しますが、b
を含みません。半開 (half-open) と表現されるのは、前の値を含むのに対し、後の値を含まないためです。閉範囲演算子と同様に、a
の値を b
より大きくすることはできません。a
と b
の値が同じ場合には、結果の範囲は空になります。
半開範囲は、配列のようなゼロベースのリストを、リストの長さまで扱うときに特に効果的です。
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
print("Person \(i + 1) is called \(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack
配列には 4 項目ありますが、半開範囲であるため、0..<count
は配列の最後のインデックスである 3 までの範囲でカウントしていることに注目してください。配列についての詳しい情報は、Arrays をご確認ください。
Portions of this page are translations based on work created and shared by Apple and used according to terms described in the Creative Commons Attribution 4.0 International License.