Find class related views in Swift

I have

class Fancy:UIButton 

and I want to find all kinds of sisters that are the same class.

I'm doing it

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

it works reliably in testing (no siblings, many, etc.)

But there are many "!" there.

Is this right in Swift?




BTW, a cool way to do this with extensions based on big answers below

Pass the type to a generic Swift extension, or ideally make it

+2
ios swift
May 14 '16 at 10:59
source share
3 answers

What about:

 for v in superview!.subviews { if let f = v as? Fancy{ print("found one") f.someProperty = 7 f.someCall() } } 
+4
May 14 '16 at 23:22
source share

How about using functional programming?

 self.superview? .subviews .flatMap { $0 as? Fancy } .filter { $0 != self } .forEach { fancy in fancy.someProperty = 4 fancy.someMethod() } 
+6
May 14 '16 at 23:41
source share

Or that:

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

@RobMayoff has a good point about excluding yourself. The code really should be:

 if let views = superview?.subviews { for aView in views { if let fancyView = aView as? Fancy where fancyView != self { fancyView.someProperty = 7 fancyView.someCall() } } } 
+1
May 14, '16 at 23:32
source share



All Articles