我试图从For循环中的数组中删除项目。为此,我按照建议here向后循环:
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
}
}
答案 0 :(得分:4)
使用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
}
}
答案 1 :(得分:4)
以下是协议的定义: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)
}
您需要提供函数distanceTo
,advancedBy
以及运算符==
和<
。在我链接的文档中有关于这些功能的更多信息。
答案 2 :(得分:1)
您应该按如下方式更改循环:
for index in stride(from: bullets!.count - 1, through: 0, by: -1) {
let bullet = bullets![index]
将bullet
赋值移动到循环内的单独语句中。