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
You must do it differently.
var arraybtnState = [Int]()
arraybtnState.append(5)
arraybtnState.append(6)
arraybtnState.removeAtIndex(0)
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
UPDATE
You can handle it like this
let some = self.strSubscribe?.componentsSeparatedByString(",").map{
(var char) -> Int in
return char.toInt() ?? 0
}
arraybtnState += some
source to share
An NSArray
is immutable. Once created, it cannot be changed.
The target NSMutableArray
to be modified.
var myArr = NSMutableArray()
myArr.addObject("hey")
You can also use Swift typed array:
var swiftArray = [String]()
swiftArray.append("hey")
EDIT:
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.
source to share
NSArray
is immutable. It cannot be changed after the announcement.
Create NSMutableArray
to be mutable.
Remove value by index
someMutableArray.removeAtIndex(2)
This will delete the value at index 2.
Delete at the end of an array
someMutableArray.removeLast()
Remove all values
someMutableArray.removeAll()
Removes all values from an array.
source to share