Swift - Insert object/item / Add object/item in NS

2020-07-10 06:48发布

问题:

I have this code:

var NToDel:NSArray = []
var addInNToDelArray = "Test1 \ Test2"

How to add addInNToDelArray in NToDel:NSArray ?

回答1:

You can't - NSArray is an immutable array, and as such once instantiated it cannot be changed. You should turn it into a NSMutableArray, and in that case it's as simple as:

NToDel.addObject(addInNToDelArray)

Alternatively, you can insert the value at instantiation time:

var NToDel:NSMutableArray = [addInNToDelArray]

but that's not about adding, it's about initializing - and in fact, after that line you cannot do any change to the array elements.

Note that there's an error in your string: the \ character must be escaped as follows:

var addInNToDelArray = "Test1 \\ Test2"