LoginSignup
0
0

More than 5 years have passed since last update.

Swiftでforループがdeprecatedになってる問題

Posted at

以下のソースコードでワーニングが出た

    func shuffle<T>(inout array: [T]) {
        for var j = array.count - 1; j > 0; j -= 1 {//この行でワーニング
            let k = Int(arc4random_uniform(UInt32(j + 1))) // 0 <= k <= j
            if k == j{
                continue
            }
            swap(&array[k], &array[j])
        }
    }

これは、配列をシャッフルする関数で、型は指定できる。

C-stype for statement is deprecated and will be removed in future version of Swift
というワーニングが出る。

ここの場合、クリックしてリターンを押して自動的に直すということができないので、手動で直すことにする。

この記事が参考になる。

// 降順ループ
var array2: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in (0 ..< array2.count).reverse() {
    array2.removeAtIndex(i)
}
print(array2)   // []

これが例文として使えるようだ

ということで、修正

    func shuffle<T>(inout array: [T]) {
        for j in (0 ..< array.count).reverse(){
            let k = Int(arc4random_uniform(UInt32(j + 1))) // 0 <= k <= j
            if k == j{
                continue
            }
            swap(&array[k], &array[j])
        }
    }

うまく動いているので良しとしておこう。

0
0
0

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