如何从元组数组中删除对象

时间:2014-11-07 13:48:07

标签: ios swift tuples

我学习Swift,我发现Arrays的功能非常有限,真的很烦人。

考虑以下元组数组:

var points = Array<(touch: UITouch, startPoint: CGPoint)>()

是否有一种无痛的方法从该数组中删除特定对象?

最接近的是removeAtIndex方法,但我无法弄清楚如何获取我的元组索引!

我试过这个,但它似乎不适用于元组,因为它们不相同:

self.points.removeAtIndex(Int(find(self.points, point)))

2 个答案:

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