1

I'm having trouble declaring a NSMutableArray in Swift 3 because using legacy objective C code bridges the swift Array data type to NSArray. Here's what I'm trying to do:

var myMutableArray: NSMutableArray = [myObjectCustomClass]

But I'm getting a compiling error:

Cannot convert value of type '[myObjectCustomClass].Type' (aka 'Array.Type' to specified type 'NSMutableArray'

I've tried a few other ways as well such as:

var myMutableArray = NSMutableArray<myObjectCustomClass>
var myMutableArray:[myObjectCustomClass] = NSMutableArray<myObjectCustomClass>

but no luck. Any ideas?

4
  • var myMutableArray = NSMutableArray()? Commented Mar 20, 2017 at 15:21
  • Yes, that declares a NSMutableArray; however, the items in the NSMutableArray should be of type myObjectCustomClass. How would I add that? Commented Mar 20, 2017 at 15:26
  • You can't, NSMutableArray lets you add objects of any type to it. That's why you use swift arrays. Commented Mar 20, 2017 at 15:27
  • Ah... ok, Dan. I see. Thanks for the info! Commented Mar 20, 2017 at 15:28

1 Answer 1

2

You have not initialised your myObjectCustomClass while declaring as a NSMutableArray that's why its showing the error. You can initialise the array at the time of declaring or can later add elements to the array as its declared var

try initialising when you declare

var myMutableArray: NSMutableArray = [myObjectCustomClass()] 
or 
var myMutableArray: [myObjectCustomClass] = [myObjectCustomClass()] //swift 3 way

or alternatively declare as a CustomClass Array variable and later add objects

 var myMutableArray: [myObjectCustomClass] = []
 let myObjectCustomClass = myObjectCustomClass()
 myMutableArray.append(myObjectCustomClass)
Sign up to request clarification or add additional context in comments.

Comments

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.