Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find sibling views of class in Swift

Tags:

ios

swift

I have a

  class Fancy:UIButton

and I want to find all the sibling views which are the same class.

I do this

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 seems to work reliably in testing (no siblings, many, etc)

But there's a lot of "!" in there.

Is this the right way in Swift?


BTW here's a cool way to do it with extensions based on the great answers below

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

like image 826
Fattie Avatar asked Dec 12 '25 08:12

Fattie


1 Answers

What about:

for v in superview!.subviews
{
    if let f = v as? Fancy{
        print("found one")
        f.someProperty = 7
        f.someCall()
    }
}
like image 102
Code Different Avatar answered Dec 14 '25 22:12

Code Different



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!