Swift:在superview中查找视图(不带for循环)

Swift:在superview中查找视图(不带for循环),swift,Swift,我使用以下代码在视图中查找某个子视图。它工作正常,for循环只运行一次,因为它只找到一个子视图满足where子句 for view in boardView.subviews where (view as? PlayingCardView)?.position.location == source. && (view as! PlayingCardView).position.column == source.column && (view as!

我使用以下代码在视图中查找某个子视图。它工作正常,for循环只运行一次,因为它只找到一个子视图满足where子句

for view in boardView.subviews where (view as? PlayingCardView)?.position.location == source.
    && (view as! PlayingCardView).position.column == source.column
    && (view as! PlayingCardView).position.row >= source.row
然而,我在这里运行一个循环,而实际上我没有做任何…循环的事情,这看起来很奇怪知道我的意思吗

有没有其他类似的搜索方法?比如使用subview.indexof:并使用where子句中的条件,或者类似的东西

另外,我知道我也可以这样做:

for view in boardView.subviews {
   if let cardView = view as? PlayingCardView {
      if cardView.position.location == source.location
        && (view as! PlayingCardView).position.column == source.column
        && (view as! PlayingCardView).position.row >= source.row {
            // Do stuff
        }
    }
}
其中一种方法的计算速度更快吗?

firstwhere:将为您提供数组中满足条件的第一个元素,假设您只想对一个元素执行此操作,因为它不是循环的:

let view = boardView.subviews.first {
    guard let cardView = $0 as? PlayingCardView else { return false }
    return cardView.position.location == source.location
            && cardView.position.column == source.column
            && cardView.position.row >= source.row
}

// do stuffs to `view`

一旦找到匹配项,它将立即停止,因此这将尽可能提高效率。但实际上,这并不重要,因为您往往只有少量的子视图。否则,GPU将首先放弃渲染所有这些内容。

我相信您正在寻找过滤方法

或者,如果您想找到满足您的参数的第一张卡片,您可以使用第一种方法


谢谢,这听起来很完美!看起来很完美。。。但是,我得到了一个错误:
if let card = (boardView.subviews as? [PlayingCardView])?.filter({
    return $0.position.location == source.location
        && $0.position.column == source.column
        && $0.position.row >= source.row
}).first {
    // Do stuff
    print(card)
}
if let card = (boardView.subviews as? [PlayingCardView])?.first(where: {
    return $0.position.location == source.location
        && $0.position.column == source.column
        && $0.position.row >= source.row
}) {
    // Do stuff
    print(card)
}