ios - 包装数组索引的最干净方法?

标签 ios arrays swift

假设我有一个包含 5 个整数的数组。如果索引递增或递减(例如)发生以下情况,那么包装数组索引的最有效方法是什么?

where n = 0: arr[n-1]//-> arr[4](从 0 回绕到数组末尾)

其中 n = 2:arr[n+1]//-> arr[3](表现正常)

where n = 4: arr[n+1]//-> arr[0](从数组末尾换行到 0)

最佳答案

您可以使用 mod 操作,这将使您达到 -count 的范围以进行计数,然后将 count 添加回去并再次进行 mod:

let foo = [0, 1, 2, 3, 4, 5]

for i in -6...7 {
  print(i, foo[(i % foo.count + foo.count) % foo.count])
}

//  -6 0
//  -5 1
//  -4 2
//  -3 3
//  -2 4
//  -1 5
//  0 0
//  1 1
//  2 2
//  3 3
//  4 4
//  5 5
//  6 0

这对两个方向都有效。

关于ios - 包装数组索引的最干净方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45397603/

相关文章:

ios - 使用 UICollectionview 创建像 Newsstand 这样的 View

ios - GPUImage 添加每个 RGB channel 的色调/颜色调整(将红色调整为更粉红色或橙色)

ios - 警告 : Attempt to present when segueing from table view

java - 如何: Converting array of bytes to InputStream

ios - 如何使用 ExpressPlay sdk 将 epub 文件集成到自己的电子书阅读器应用程序中?

javascript - 查找 JavaScript 数组中缺失的数字

javascript - 内爆 :Invalid arguments in an array?

ios - 重用 UIView 会导致应用卡住

swift - 使用swift 4自动登录网页

ios - 字符串不可转换为 DictionaryIndex<String, AnyObject>