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];
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).
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 .
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.
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.
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
)
*/
You can do the same thing in swift, just modify the syntax a bit:
var arr = NSArray()
var mutableArr = NSMutableArray(array: arr)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With