Fattie
Fattie

Reputation: 12287

Find sibling views of class in 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

Upvotes: 2

Views: 1394

Answers (3)

Duncan C
Duncan C

Reputation: 131491

Or this:

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

Upvotes: 1

Luca Angeletti
Luca Angeletti

Reputation: 59536

What about using functional programming?

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

Upvotes: 6

Code Different
Code Different

Reputation: 93191

What about:

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

Upvotes: 5

Related Questions