【问题标题】:Swift For Loops using Closed Range使用封闭范围的 Swift For 循环
【发布时间】:2017-08-05 06:18:55
【问题描述】:

我有一个for 循环并想要访问“当前”索引。 Xcode 给了我恼人的错误。

for k in [1...map.dates.count-1]
{
    map.returns.append((map.closingPrices[k]-map.closingPrices[k-1])/map.closingPrices[k-1])
}

所以我基本上在做的是for k in [1..10],计算返回值 (b-a)/a,其中 b 和 a 是某个数组中的连续元素 (closingPrices)。

编译器对我使用k 访问closingPrices 没有问题,但是当我使用k-1 时它会感到不安,因为k 不是整数,而是CountableClosedRange<Int>

错误提示

二元运算符“-”不能应用于 CountableClosedRange 和 Int 类型。

所以 - 简单的问题 - 我如何重写我的代码以访问 k 的整数值并从中减去 1 而不会出现编译器错误。

【问题讨论】:

  • 你可能想要for k in 1...map.dates.count-1 {...},不带方括号。
  • 是的,对不起,我只是因为那里的语法错误!非常感谢。请将其发布为答案。
  • 你也可以说for k in 1..<map.dates.count让它看起来更干净一些,虽然它和1...map.dates.count-1完全一样。
  • map.returns = zip(map.closingPrices, map.closingPrices.dropFirst()).map { ($1 - $0)/$0 } - 不需要索引:)
  • 喜欢那里的单线!

标签: swift for-loop integer


【解决方案1】:
[1...map.dates.count-1]

返回包含单个范围的 array,因此您的循环计数器不是您期望的整数,而是范围对象。只需删除方括号就可以了:

for k in 1...map.dates.count-1
{
    map.returns.append((map.closingPrices[k]-map.closingPrices[k-1])/map.closingPrices[k-1])
}

【讨论】:

  • 如果你减去-1,那么你可以直接使用1 ..< map.dates.count。或类似map.dates.indices.dropFirst().
猜你喜欢
  • 2011-01-28
  • 2021-11-05
  • 2020-03-30
  • 2021-01-24
  • 2021-05-02
  • 2012-12-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
相关资源
最近更新 更多