8
8

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.

[Swift]Rangeを使ったforループは気をつけよう

Last updated at Posted at 2014-07-23

環境:Xcode6 beta 4

(a...b)(a..<b) などのRange Operatorで、 startIndexendIndex より大きい場合、forループで使うと無限ループになります

// 無限ループ
for i in 10..<9 {
  println(i)
}

直接リテラルでこのように書く人はいないでしょうが、こんなケースでは注意が必要です。

func copyArray<T>(source: [T], padding: T, length: Int) -> [T] {
  let sourceCount = source.count
  var result = [T]()
  
  for element in source {
    result.append(element)
  }
  
  // souceCount > lengthの時に無限ループ
  for _ in sourceCount..<length {
    result.append(padding)
  }
  return result
}

let threeWords = ["one", "two", "three"]
let fiveWords = copyArray(threeWords, "zero", 5) // ["one", "two", "three", "zero", "zero"]
let twoWords = copyArray(fiveWords, "zero", 2) // 無限ループ

こういう挙動って期待してないんですが、バグではなくて仕様なんでしょうか?

8
8
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
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?