0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Basic Operators - Range Operator

Posted at

Swift では2つの 範囲演算子 range operator を用意している。

Closed Range Operator

Closed Range Operator (a...b) は、a から b までの範囲の値を対象とする。
利用上の注意は

  • closed range operator は a, b 両方の値を対象範囲とする。
  • a は b よりも低い数値でなければいけない。

closed range operator は for-in ループなどで有用。

for index in 1...5 {
	print("\(index) times 5 is \(index * 5)")
}
// 1 time 5 is 5
// 2 time 5 is 10
// 3 time 5 is 15
// 4 time 5 is 20
// 5 time 5 is 25

for-in ループの詳細については Control Flow を参考にすること。

Half-Open Range Operator

*Half-Open Range Operator (a..<b) は a 以上、b 未満 の範囲を対象とする。

利用上の注意は

  • Half-open range operator は a 以上、 b 未満の値を対象範囲とする。
  • a は b よりも低い数値でなければいけない。

Half-open range operator は 配列などの値を全てを対象にした処理の際に有用。

let names = ["Anna", "Alex", "Brian", "Jack"]
for i in 0..<names.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

配列 names の値は4つあるが、最後のインデックスは3なので、「未満」で処理してくれるHalf-open range operator を使うと楽。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?