我正在尝试从 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
}
}
最佳答案
这是协议(protocol)的定义: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
和运营商==
和 <
.我链接的文档中有关于这些功能的更多信息。
关于ios - 如何在 Swift 中遵守 Strideable 协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27024603/