Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NSArray to NSMutableArray Swift

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];
like image 238
Peter Pik Avatar asked Sep 17 '14 21:09

Peter Pik


People also ask

Can we use NSArray in Swift?

In Swift, the NSArray class conforms to the ArrayLiteralConvertible protocol, which allows it to be initialized with array literals. For more information about object literals in Swift, see Literal Expression in The Swift Programming Language (Swift 4.1).

What is NSMutableArray in Swift?

Overview. The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray .

What is difference between array and NSArray in Swift?

Array is a struct, therefore it is a value type in Swift. NSArray is an immutable Objective C class, therefore it is a reference type in Swift and it is bridged to Array<AnyObject> . NSMutableArray is the mutable subclass of NSArray . Because foo changes the local value of a and bar changes the reference.

What is NSArray?

NSArray is Objective-C's general-purpose array type. It represents an ordered collection of objects. NSArray is immutable, so we cannot dynamically add or remove items. Its mutable counterpart, NSMutableArray, will be discussed in the second part of this tutorial.


2 Answers

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
)
*/
like image 89
Imanou Petit Avatar answered Sep 19 '22 20:09

Imanou Petit


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

var arr = NSArray()
var mutableArr = NSMutableArray(array: arr)
like image 40
Connor Avatar answered Sep 19 '22 20:09

Connor