2017-02-04 96 views
0

我使用以下代碼在我的視圖中查找某個子視圖。它工作正常,並且for循環僅運行一次,因爲它只找到一個滿足where子句的子視圖。Swift:在超視圖中查找視圖(不包含for循環)

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 

然而,似乎不可思議的是我運行一個循環這裏的時候,我實際上沒有做任何...循環-Y的東西(知道我的意思)?

有沒有其他的方式來像這樣「搜索」?像使用subviews.index(of:)並使用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 
     } 
    } 
} 

是通過下列方式之一計算更快?

回答

1

我相信你正在尋找filter方法。

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

或者,如果你想找到滿足你的論點的第一張牌,你可以使用first方法。

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) 
} 
+1

謝謝,這聽起來相當完美! –

+0

好吧,它看起來很完美...但是我得到一個錯誤: –

+0

什麼是錯誤? – Callam

0

first(where:)會給你滿足條件(假設你只想做一個元素,因爲它不是「糊塗」)數組中的第一個元素:

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將首先渲染所有渲染。