我知道如何找到一个包含两个数组相同元素的数组,即
let resultArray = firstArray.filter(secondArray.contains)
但如果firstArray
和secondArray
都是CGPoint
数组,如何在两者中找到包含相同x值的元素?
答案 0 :(得分:1)
如果您不想分配持有CGPoint
点x
的额外secondArray
数组,您可以使用以下备选方案
let resultAlt1 = firstArray
.filter { pt in secondArray.reduce(false) { $0 || $1.x == pt.x } }
reduce
的短路可能无法明确地实现这一点,因此如果性能成为问题,另一种选择是
let resultAlt2 = firstArray.filter {
for pt in secondArray {
if pt.x == $0.x { return true }
}
return false
}
这实质上与使用contains
的其他答案相同,但不需要中间x
点数组。
答案 1 :(得分:0)
//your data
let search = [CGPoint(x: 0, y: 1), CGPoint(x: 1, y: 1), CGPoint(x: 0, y: 2), CGPoint(x: 3, y: 3)]
let queryPoints = [CGPoint(x: 0, y: 1), CGPoint(x: 1, y: 1)]
//actual search
let queryX = queryPoints.map{ $0.x }
let result = search.filter{ queryX.contains($0.x) }
答案 2 :(得分:0)
let secoundArrayXPoints = secondArray.map{$0.x}
let resultArray = firstArray.filter{ secoundArrayXPoints.contains($0.x) }
答案 3 :(得分:0)
let arrA: [CGPoint] = [CGPoint(x: 10, y: 10), CGPoint(x:15, y: 20), CGPoint(x: 20, y: 20)]
let arrB: [CGPoint] = [CGPoint(x: 10, y: 30), CGPoint(x:40, y: 20), CGPoint(x: 20, y: 30)]
let arrAx = arrA.map({ $0.x })
let arrC = arrB.filter({arrAx.contains($0.x) } )