Convert NSArray to NSMutableArray Swift

I am trying to convert self.assets NSArray to NSMutableArray and add it to picker.selectedAssets , which is NSMutableArray . How will this code look fast?

Objective-C Code

 picker.selectedAssets = [NSMutableArray arrayWithArray:self.assets]; 
+7
objective-c swift
source share
2 answers

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

 convenience init(array anArray: NSArray) 

Initializes a newly allocated array, placing the objects contained in this array into it.


The following Playground code example shows NSMutableArray create an NSMutableArray instance from an NSArray instance:

 import Foundation let nsArray = [12, 14, 16] as NSArray var nsMutableArray = NSMutableArray(array: nsArray) print(nsMutableArray) /* prints: ( 12, 14, 16 ) */ 
+26
source share

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

 var arr = NSArray() var mutableArr = NSMutableArray(array: arr) 
+3
source share

All Articles