0

I'd like to figure out how to specify or cast an NSMutableArray to a swift Array of a custom type. I currently have 2 files:

  1. First file requires an NSMutableArray for its functionality (passed by reference, ability to remove particular objects with indices I don't know)
  2. Second file uses a Swift array (better memory / throwaway array), with a custom type, which I declare using

let newArray: [CustomType]!

I need to pass the NSMutableArray in as a parameter to a function in the second file, which requires a [CustomType]. When simply calling it:

let newVC = UIViewController(array: mutableArray)

it keeps telling me 'CustomType' is not identical to 'AnyObject'. I've tried calling the function using mutableArray as [CustomType], which does not work either. How can I make the swift Array function accept my NSMutableArray?

1

2 Answers 2

3

This works for me:

var swiftArray = NSArray(array:mutableArray) as Array<CustomType>

swiftArray is then a Swift array of objects of CustomType. You can pass the array and iterate over it as you would expect.

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

1 Comment

Note this only works if your NSMutableArray contains CustomType objects.
1

What I needed was this:

let newVC = UIViewController(array: mutableArray as AnyObject as [CustomType])

1 Comment

Cool, that is very compact syntax.

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.