Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add/Remove Object at index swift

Tags:

ios

swift

I have one array like

var arraybtnState: NSArray! = NSArray()  

For add/Remove object into array, I had cast it in to NSMutableArray...

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

But it gives me SIGABRT error:

Could not cast value of type 'Swift._SwiftDeferredNSArray' (0x453e08) to 'NSMutableArray'

I have already tried NSMutableArray but it gives me error in below line

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

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

like image 765
EI Captain v2.0 Avatar asked Oct 24 '25 04:10

EI Captain v2.0


2 Answers

You should do it in a different way

var arraybtnState = [Int]()
arraybtnState.append(5)
arraybtnState.append(6)
arraybtnState.removeAtIndex(0)

While you declaring it like so

 var arraybtnState:NSArray! = NSArray()  

you are creating pure NSArray type and it indeed cannot be casted to NSMutableArray

UPDATE

You can deal with it as follows

let some = self.strSubscribe?.componentsSeparatedByString(",").map{
    (var char) -> Int in
    return char.toInt() ?? 0
}
arraybtnState += some
like image 114
Azat Avatar answered Oct 26 '25 20:10

Azat


An NSArray is immutable. Once created, it can't be modified.

That's the purpose of NSMutableArray, to be modifiable.

var myArr = NSMutableArray()
myArr.addObject("hey")

You also could use a Swift typed array:

var swiftArray = [String]()
swiftArray.append("hey")

EDIT:

There's something screwy going on with the compiler. I think there's 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 it complains

[String]? is not convertible to 'NSArray'

Suggesting that in Swift, componentsSeparatedByString returns a string array optional ([String]?]).

If that was the case, you should be able to fix it like this:

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

But that gives this error:

error: operand of postfix '!' should have optional type; type is '[String]'

Very strange.

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

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

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

This code does work:

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

That is your solution.

like image 40
Eric Aya Avatar answered Oct 26 '25 19:10

Eric Aya