我学习Swift,我发现Arrays的功能非常有限,真的很烦人。
考虑以下元组数组:
var points = Array<(touch: UITouch, startPoint: CGPoint)>()
是否有一种无痛的方法从该数组中删除特定对象?
最接近的是removeAtIndex
方法,但我无法弄清楚如何获取我的元组索引!
我试过这个,但它似乎不适用于元组,因为它们不相同:
self.points.removeAtIndex(Int(find(self.points, point)))
答案 0 :(得分:3)
我建议你放弃元组并使用你自己的结构:
struct TouchPoint: Equatable {
var touch: UITouch
var startPoint: CGPoint
init(touch: UITouch, startPoint: CGPoint) {
self.touch = touch
self.startPoint = startPoint
}
}
为==
类型定义TouchPoint
以满足Equatable
协议:
func ==(lhs: TouchPoint, rhs: TouchPoint) -> Bool {
return (lhs.touch == rhs.touch) && (lhs.startPoint == rhs.startPoint)
}
然后您可以像这样使用TouchPoint
:
var arr = [TouchPoint]()
let tp1 = TouchPoint(touch: UITouch(), startPoint: CGPointMake(1, 2))
let tp2 = TouchPoint(touch: UITouch(), startPoint: CGPointMake(3, 4))
arr.append(tp1)
arr.append(tp2)
由于TouchPoint
类型为Equatable
,您可以使用find
查找和删除商品:
if let index = find(arr, tp2) {
arr.removeAtIndex(index)
}
答案 1 :(得分:2)
这可能是一种方法:
let point1 = (touch: UITouch(), startPoint: CGPoint(x: 0, y: 0))
let point2 = (touch: UITouch(), startPoint: CGPoint(x: 1, y: 1))
var points: [(touch: UITouch, startPoint: CGPoint)] = []
points += [point1, point2]
// delete point2
points = points.filter { !($0.touch == point2.touch && $0.startPoint == point2.startPoint) }