Can I create a class that subclasses from Array?

I am fiddling around with making a cocoapod, and I am trying to make a class that sub-classes from type Array.

The reason I wan it to sub-class from Array, is because Array and NSArray are treated differently in Swift.

I can create a class like this:

class Test : NSArray {}

But if I try this:

class Test : Array {}

Or this:

class Test : [AnyObject] {}

I get an error.

Mostly the reason I want this is so I can use functions like this:

let i = myArray.randomObject()

Versus this:

let i = Test.randomObject(myArray)

Any ideas of what I could do (instead maybe)?


You can add methods to Array via an extension. Something like:

extension Array
    func randomObject() -> Element { return self[ Int( arc4random_uniform( UInt32( self.count ) ) ) ] }

Now you can do myArray.randomObject() where myArray is of type Array

Edit: Also, @Addison correctly pointed out that struct types cannot be subclassed in Swift.

You cannot subclass Array because it is a struct. An NSArray however, is an object so you can subclass that. I'm not sure what you are trying to accomplish, but you may want to conform to the CollectionType protocol instead, which both structs and objects can do, as well as enums.

Need Your Help

connect uiview to uiviewcontroller

objective-c xcode uiview uiviewcontroller

i try to create 2 players game for the ipad, the game should be a multiplayer game (one player vs other player on the same device). now, i need to add for my main viewcontroller two uiviews that ea...

JQuery Hide and Showing Tabs Content

jquery html show-hide

I have a problem with the JQuery Hiding and showing tabs