2016-05-14 25 views
2

同胞的意見類的我有一個查找斯威夫特

class Fancy:UIButton 

,我想找到它們是同一類的所有兄弟姐妹的意見。

我這樣做

for v:UIView in superview!.subviews 
    { 
    if v.isKindOfClass(Fancy) 
     { 
     // you may want... if (v==self) continue 
     print("found one") 
     (v as! Fancy).someProperty = 7 
     (v as! Fancy).someCall() 
     } 
    } 

它似乎在測試中可靠地工作(沒有兄弟姐妹很多,等)

但是有一個很大的「!」在那裏。

這是Swift中的正確方法嗎?


BTW這裏是基於偉大的答案擴展做下面一個很酷的方式

Pass in a type to a generic Swift extension, or ideally infer it

+0

強制解包是危險的,應該避免。如果失敗,就會崩潰。你的內在力量 - 解開'(v!!Fancy)'是保存,但不雅。 –

+0

嗨@DuncanC,你很確定它是安全的? (我們稍後可以處理的Inelegant :)) – Fattie

+0

內部是強制向下投射,而不是強制解開。我錯過了。是的,這是安全的,因爲你有它在一個if語句中檢查v –

回答

4

什麼:

for v in superview!.subviews 
{ 
    if let f = v as? Fancy{ 
     print("found one") 
     f.someProperty = 7 
     f.someCall() 
    } 
} 
+0

類嘗試''在超視圖v?.subviews? []'擺脫最後一個'!'。 –

+0

另外'如果讓f = v as?如果你想跳過「自我」,那麼花在f!= self'的地方。 –

+0

我覺得這是最簡單,不太簡潔,不太羅嗦的Swift習語的答案。再次感謝所有人。 – Fattie

1

或者這樣:

if let views = superview?.subviews 
{ 
    for aView in views 
    { 
    if let fancyView = aView as? Fancy 
    { 
     fancyView.someProperty = 7 
     fancyView.someCall() 
    } 
    } 
} 

@RobMayoff關於排除自我有一個很好的觀點。該代碼真的應該是:

if let views = superview?.subviews 
{ 
    for aView in views 
    { 
    if let fancyView = aView as? Fancy where fancyView != self 
    { 
     fancyView.someProperty = 7 
     fancyView.someCall() 
    } 
    } 
} 
+0

就我個人而言,我喜歡@ appzYourLife的功能版本,但您應該接受其中的一個*。 –

+0

這是一個非常可惜的人不能寫,因爲它是:'爲aView as?在視圖中花式' – Fattie

+0

所以你想要一個for循環與'as?'投射做一個隱式過濾器?那會很方便。 –

6

有關使用函數式編程什麼?

self.superview? 
    .subviews 
    .flatMap { $0 as? Fancy } 
    .filter { $0 != self } 
    .forEach { fancy in 
     fancy.someProperty = 4 
     fancy.someMethod() 
    } 
+0

這個答案是我的最愛。 (投票)。我需要教我自己去思考功能性編程風格。 –

+0

@DuncanC:謝謝,我明白這一點。 –

+0

是一個很好的擴展! http://stackoverflow.com/questions/37240091/pass-in-a-type-to-a-generic-swift-extension – Fattie