How to add / remove an object at index swift

I have one array like

var arraybtnState: NSArray! = NSArray()  


To add / remove an object to an array, I included it in NSMutableArray


(self.arraybtnState as! NSMutableArray).addObject(button.tag)  
(self.arraybtnState as! NSMutableArray).removeObject(button.tag)  


But this gives me an error SIGABRT


Failed to pass value of type "Swift._SwiftDeferredNSArray" (0x453e08) to "NSMutableArray"

I already tried NSMutableArray

it but it gives me an error on the line below

self.arraybtnState = self.strSubscribe?.componentsSeparatedByString(",") 


The question is what is the preferred way to add / remove an object in array


source to share

4 answers

You must do it differently.

var arraybtnState = [Int]()


As long as you declare it like this

 var arraybtnState:NSArray! = NSArray()  


you are creating a pure type NSArray

and it really cannot be added toNSMutableArray


You can handle it like this

let some = self.strSubscribe?.componentsSeparatedByString(",").map{
    (var char) -> Int in
    return char.toInt() ?? 0
arraybtnState += some




An NSArray

is immutable. Once created, it cannot be changed.

The target NSMutableArray

to be modified.

var myArr = NSMutableArray()


You can also use Swift typed array:

var swiftArray = [String]()



Something strange is happening in the compiler. I think there is a bug in Xcode 6.3 / Swift 1.2.

This code should work:

let aString: String? = "One, Two, Three" let array = aString? .ComponentsSeparatedByString (",") as NSArray

But he complains

[String]? does not convert to 'NSArray'

Assuming in Swift the SeparatedByString components return an optional string array ( [String]?]


If so, you can fix it like this:

let array = aString? .componentsSeparatedByString (",")! like NSArray

But , which gives this error:

error: postfix operand '!' must be of an optional type; type - '[String]'

Very strange.

If you look in the headers, the Swift definition in SwiftSearatedByString () is

func componentsSeparatedByString(separator: String) -> [String]


It's pretty clear that componentsSeparatedByString () returns a Swift String array, not optional. The compiler complains about any syntax.

This code works :

let string1:String? = "One,Two,Three"
let array1 = string1?.componentsSeparatedByString(",")
let aMutableArray = (array1! as NSArray).mutableCopy()
  as! NSMutableArray


It's your decision.



Please write in the selected cell function. this will automatically delete the cell. when you select a cell

arryName.remove (indexPath.row)




is immutable. It cannot be changed after the announcement.

Create NSMutableArray

to be mutable.

Remove value by index



This will delete the value at index 2.

Delete at the end of an array



Remove all values



Removes all values ​​from an array.



All Articles