0

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)?

1
  • 1
    What are you trying to accomplish here? From your example it sounds like you want an extension rather than a subclass. Commented Mar 15, 2016 at 22:18

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Note that arc4random_uniform expects an argument of type UInt32, wheras self.count returns Int. The same holds for the subsequent access of an index in self: index expects type Int (int case of indexable), whereas arc4random_uniform returns type UIn32. So you'll need to include some type conversions/initializations in your example above.
0

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.

3 Comments

You cannot easily subclass NSArray since it's a class cluster. When you create an NSArray/NSMutableArray the class of the returned object may be one of several private implementation classes.
In any case, better to be able to use standard Array/NSArray in your code everywhere and extend it via extensions than to have to use a custom subclass of Array/NSArray everywhere.
Ok thanks, I never knew that NSArray was a class custer. Yeah I agree that it's better to just use an extension rather than create a new class or subclass one, but I wanted to explain why you can't subclass Array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.