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
What about:
for v in superview!.subviews
{
if let f = v as? Fancy{
print("found one")
f.someProperty = 7
f.someCall()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With