如何在 Swift 中遵守 Strideable 协议?

Jan*_*Jan 2 xcode protocols ios swift

我正在尝试从 For 循环内的数组中删除项目。为此,我按照此处的建议向后循环,如下所示:

for (index, bullet:Bullet) in stride(from: bullets!.count - 1, through: 0, by: -1) {
    if(currentTime - bullet.life! > bullet.maxLife){
        bullet.removeFromParent()
        bullets?.removeAtIndex(index)
    }
}
Run Code Online (Sandbox Code Playgroud)

但我收到错误

Type '($T12, Bullet)' does not conform to protocol 'Strideable'
Run Code Online (Sandbox Code Playgroud)

更新

这是子弹的类。这是一个 Cocos2D 应用程序,因此是 CCDrawNode 类型。

import Foundation

  class Bullet: CCDrawNode {
  var speed:CGPoint?
  var maxSpeed:CGFloat?
  var angle:CGFloat?
  var life:CGFloat?
  var maxLife:CGFloat = 0.5

  init(angle: CGFloat){
    super.init()
    self.drawDot(ccp(0,0), radius: 2, color: CCColor.whiteColor());

    self.contentSize = CGSize(width: 4, height: 4)
    self.angle = angle
    maxSpeed = 10
    speed = CGPoint(x: maxSpeed! * CGFloat(sin(angle)), y: maxSpeed! * CGFloat(cos(angle)))

  }

  override func update(delta: CCTime) {
    self.position.x += speed!.x
    self.position.y += speed!.y
  }

}
Run Code Online (Sandbox Code Playgroud)

小智 5

这是协议的定义:Stridable

你可以这样实现:

final class Foo: Strideable {
  var value: Int = 0
  init(_ newValue: Int) { value = newValue }
  func distanceTo(other: Foo) -> Int { return other.value - value }
  func advancedBy(n: Int) -> Self { return self.dynamicType(value + n) }
}

func ==(x: Foo, y: Foo) -> Bool { return x.value == y.value }
func <(x: Foo, y: Foo) -> Bool { return x.value < y.value }

let a = Foo(10)
let b = Foo(20)

for c in stride(from: a, to: b, by: 1) {
  println(c.value)
}
Run Code Online (Sandbox Code Playgroud)

您需要提供函数distanceToadvancedBy运算符==<。我链接的文档中有有关这些功能的更多信息。