LoginSignup
2
0

More than 5 years have passed since last update.

swiftの配列からindexを循環して取得

Last updated at Posted at 2019-01-17

なんてタイトルにしていいか分からなくて困った
pythonみたいに負の値でもうまくとりたいなって

extension

extension Array{
  subscript (loop index: Int) -> Element {
    let lIndex = (self.count + (index % self.count)) % self.count
    return self[lIndex]
  }
}

使い方

  let a = [1,2,3,4,5]
  for index in -10 ... 10{
    print("\(index), \(a[loop:index])")
  }
/*
index = -10, value = 1
index = -9, value = 2
index = -8, value = 3
index = -7, value = 4
index = -6, value = 5
index = -5, value = 1
index = -4, value = 2
index = -3, value = 3
index = -2, value = 4
index = -1, value = 5
index = 0, value = 1
index = 1, value = 2
index = 2, value = 3
index = 3, value = 4
index = 4, value = 5
index = 5, value = 1
index = 6, value = 2
index = 7, value = 3
index = 8, value = 4
index = 9, value = 5
index = 10, value = 1
*/

おわり

いまどきindexで配列にアクセスするな

2
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
2
0