9

I'm trying to convert a the self.assets NSArray to NSMutableArray and add it to picker.selectedAssets which is a NSMutableArray. How will this code look like in swift?

Objective-C Code

picker.selectedAssets = [NSMutableArray arrayWithArray:self.assets];
1
  • Without bothering to look at the docs, I imagine NSMutableArray(self.assets) and/or NSMutableArray.arrayWithArray(self.assets) would do it. Commented Sep 17, 2014 at 21:25

2 Answers 2

29

With Swift 5, NSMutableArray has an initializer init(array:) that it inherits from NSArray. init(array:) has the following declaration:

convenience init(array anArray: NSArray)

Initializes a newly allocated array by placing in it the objects contained in a given array.


The following Playground sample code shows hot to create an instance of NSMutableArray from an instance of NSArray:

import Foundation

let nsArray = [12, 14, 16] as NSArray
let nsMutableArray = NSMutableArray(array: nsArray)
nsMutableArray.add(20)
print(nsMutableArray)

/*
prints:
(
    12,
    14,
    16,
    20
)
*/
Sign up to request clarification or add additional context in comments.

5 Comments

imagePicker.selectedAssets = NSMutableArray(array: self.assets!) Returns: fatal error: unexpectedly found nil while unwrapping an Optional value
By reading your comment, I guess that self.assets is in fact of type NSArray?. If so, you should perform an optional binding before assigning it to your NSMutableArray.
optional binding could i explain?
Have a look here then try the following code: if assets = self.assets {picker.selectedAssets = NSMutableArray(array: assets)}.
This line is such a beauty , "let nsMutableArray = NSMutableArray(array: nsArray)" , simple but effective ; thank you sir for this answer
3

You can do the same thing in swift, just modify the syntax a bit:

var arr = NSArray()
var mutableArr = NSMutableArray(array: arr)

2 Comments

Should it be let arr?
it could also be let. Since both arrays are only initialized in the snippet, they could both use let. It depends on how you use them after

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.