Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the swift equivalent of makeObjectsPerformSelector?

Tags:

xcode

ios

swift

In Objective-C I'm using this code to remove any sub-views:

[self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

But how to use it in swift? I saw apple documentation to use that method in swift

func makeObjectsPerformSelector(_ aSelector: Selector)

but when I try it, I get an error: 'AnyObject[]' does not have a member named 'makeObjectsPerformSelector'

Are there any ways to remove sub-views in swift?

like image 217
yumugee Avatar asked Jun 27 '14 07:06

yumugee


3 Answers

Updated for Swift 2.0 (Xcode 7)

Use forEach:

self.view.subviews.forEach { subview in
    subview.removeFromSuperview()
}

Or like this:

view.subviews.forEach { $0.removeFromSuperview() }
like image 171
rob mayoff Avatar answered Oct 18 '22 11:10

rob mayoff


It only works on NSArray and NSMutableArray objects.

This will work:

let ar: NSArray = [obj1, obj2, obj3]
ar.makeObjectsPerformSelector("someSelector")

Note that if you have an Array<AnyObject> you can freely convert to NSArray and vise versa.

let anNSArray: NSArray = anArrayOfAnyObject
anNSArray.makeObjectsPerformSelector( "someSelector")
like image 1
Bruce1q Avatar answered Oct 18 '22 09:10

Bruce1q


As of Xcode 7, the full family of performSelector methods are available in Swift, including makeObjectsPerformSelector() for NSArray.

like image 1
FizzBuzz Avatar answered Oct 18 '22 11:10

FizzBuzz