簡體   English   中英

如何遵循Swift中的Strideable協議?

[英]How can I conform to the Strideable protocol in 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)
    }
}

但是我出錯了

Type '($T12, Bullet)' does not conform to protocol 'Strideable'

更新

這是子彈班。 這是一個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
  }

}

使用filter()方法的替代解決方案,完全不需要索引:

bullets!.filter { bullet -> Bool in
    if (currentTime - bullet.life! > bullet.maxLife) {
        bullet.removeFromParent()
        return false // remove from array
    } else {
        return true // keep in array
    }
}

這是協議的定義:可填充

您可以這樣實現:

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)
}

您需要提供distanceToadvancedBy函數和運算符==< 我鏈接的文檔中有關於這些功能的更多信息。

您應該按以下方式更改循環:

for index in stride(from: bullets!.count - 1, through: 0, by: -1) {
    let bullet = bullets![index]

通過將bullet分配移動到循環內的單獨語句中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM