How to Sort using NSMutableArray? - ios

I am trying to sort the NSMutableArray with this piece of code
let sortContacts = contactData! as NSArray as? [String]
print("\(sortContacts.sort())")
I am trying to convert the NSMutableArray to Array of String but when it comes to print("\(sortContacts.sort())") its giving me nil
Anyone who can suggest me sorting through NSMutableArray?

The class NSMutableArray has several sort methods. You should read the documentation. One of the sort methods is this one.
By the way: a ! in Swift code is a code smell.

This works, just make sure your NSMutableArray contains only string, else use if let:
let contactData = NSMutableArray(array: ["c","b","a"])
let sortContacts = contactData as NSArray as! [String]
print(sortContacts.sort())

Related

Ambiguous use of 'mutableCopy()' Swift3

I tried to update Swift 3 and I got the following error :
Ambiguous use of 'mutableCopy()'
Before update to swift 3. It runs well.
Swift 2.3
NSUserDefaults.standardUserDefaults().objectForKey("listsavednews")?.mutableCopy() as! NSMutableArray
Swift 3.0
(UserDefaults.standard.object(forKey: "listsavednews")? as AnyObject).mutableCopy() as! NSMutableArray
I found that mutableCopy in Swift3 return Any that doesnt have method mutableCopy() so that it needs to cast to AnyObject.
Any helps thanks.
I dont know why I can't comment.
Thanks all, I'll be using :
UserDefaults.standard.mutableArrayValue(forKey: "listsavednews")
mutableCopy is an Objective-C method from NSObject. There's little reason to use it in Swift 3.
Since you are dealing with UserDefaults and mutableCopy, you must be dealing with either an array or dictionary. Or it could be a string.
The proper way to do this in Swift 3 is to use the proper UserDefaults method to get an array or dictionary. And assign the result to a var. That combination will give you a mutable array or mutable dictionary.
var someArray = UserDefaults.standard.array(forKey: "somekey")
or:
var someDictionary = UserDefaults.standard.dictionary(forKey: "somekey")
In the two above cases, you end up with an optional since there might not be any data for the given key. And you also get a non-specific array or dictionary which isn't ideal. It would be better to cast the result to the appropriate type.
Let's say you have an array of strings and you want an empty array if there is nothing currently in user defaults. You can then do:
var someArray = UserDefaults.standard.array(forKey: "somekey" as? [String]) ?? []
Adjust as necessary if the array contains something other than String.
If you actually have a dictionary, the code would be similar.
var someDictionary = UserDefaults.standard.dictionary(forKey: "somekey") as? [String:String] ?? [:]
If your original object is just a string, then you could do:
var someString = UserDefaults.standard.string(forKey: "somekey") ?? ""

NSFastEnumerationIterator.Element (aka Any) has no subscript members

after updating xcode to 8 version, I got this error
searchArray = allArray.filter({$0["test"] as? String == findCode
let resultText: NSString = ($0["test"] as? String)
return (resultText.range(of: searchText, options: NSString.CompareOptions.caseInsensitive).location) != NSNotFound
}) as NSArray!
Any thoughts?
The ultimate source of your problem is this line:
var allArray : NSArray!
NSArray is an Objective-C class. You are trying to write Objective-C code in Swift. Don't. This is Swift. Use Swift types! Write Swift code!
This is presumably an array of something. Swift needs to know what that is. For example, if this is an array of dictionaries, than its type would be [[AnyHashable:Any]]. If you use Swift types, your code will just work, because Swift will know what the elements of your arrays are.

Swift NSMutableArray add one more array

The Problem is First time I get data from WebServices so I have show this data on TableView Then user scroller down tableview then again call WebSevices and add this data to again in array
but when I try to add data again in nsmutable type array app is crashing
Here is my code. Any solution?
1st time Data load is Working
var ary_mutable: NSMutableArray!
ary_mutable = NSMutableArray()
ary_mutable=jsonResult as AnyObject as! NSMutableArray
self.tbl_T.reloadData();
self.tbl_T.delegate=self;
self.tbl_T.dataSource=self;
2nd Time data load and add with old array not Working
var myArray :NSArray!
myArray = jsonResult as AnyObject as! NSArray
ary_mutable.addObject(myArray.objectAtIndex(0))
Got This Error
[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'
I have Try this code also But Not Working
ary_mutable.addObject(myArray)
You should create a mutable array from immutable. This:
ary_mutable=jsonResult as AnyObject as! NSMutableArray
does not do it, it is just a static cast from one type to another. You have to construct a new NSMutableArray and then fill it with required values.
Change your code to
var ary_mutable = NSMutableArray()
// everytime you receive a new data
ary_mutable.addObjectsFromArray(jsonResult as! [AnyObject])
replace this code:
var myArray :NSArray!
myArray = jsonResult as AnyObject as! NSArray
ary_mutable.addObject(myArray.objectAtIndex(0))
with this code:
var myArray : NSMutableArray!
myArray = jsonResult as AnyObject as! NSMutableArray
ary_mutable.addObjectsFromArray(myArray as [AnyObject]);

Swift Array addObjects to NSMutableArray

I have a Swift Array and I want to add all the objects inside to NSMutableArray
let stringName: String = "Something"
let stringNameSeperated = Array(logoName)
let mutableStringName: NSMutableArray = NSMutableArray(array: stringNameSeperated)
How can I do that?
I'm not really sure what you wanted to archive, but if you just wanted a Swift.Character sequence array, here's a simpler way without even the Array() process: (Notice that the result was casted into String. If you want Character, you will have to modify the code a bit.)
let stringName: String = "Something"
let mutableStringName: NSMutableArray = NSMutableArray(array: map(stringName) { String($0) } )
And from my understanding, you no longer have to case between Swift Array and Objective-C Array, you can use them interchangeably. Also, you can pass a Swift Array to a parameter that expected to be NSArray without problem in Swift 1.x as well.

EXC_BAD_INSTRUCTION object array assign Swift

I have an array of Printable objects, but I need them Equatable and AnyObject compliant.
private(set) var items: [Printable] = []
class func withItems<T: AnyObject where T: Equatable, T: Printable>(items: [T], selectedItem: T? = nil) {
... instance init ...
instance.items = items
}
And it result on EXC_BAD_INSTRUCTION:
fatal error: array cannot be bridged from Objective-C
This is one try to this problems:
Generic function and attribute with Equatable and Printable as parameters in Swift
why?
A Swift Array must contain all one kind of object (e.g. all String or all Int). An Objective-C NSArray can contain many different kinds of objects (e.g. some NSStrings and some NSNumbers). Hence if you get that kind of array from Objective-C you can't magically assign it into a Swift array reference.
What I do in that situation is munge the array to make it acceptable to Swift. I don't know what the details are of what you're getting back from Objective-C; your actual strategy will depend on those details and what you want to do with the array. One approach is to assign / cast into a Swift array of AnyObject. Or you might decide to leave it as an NSArray and work with it entirely through NSArray methods.
Here's an example from my own code. arr is an NSArray that's a mixed bag of NSString and NSNull objects. I know none of the NSString objects are the empty string, so I substitute the empty string for all the NSNull objects, thus giving me an array of just strings, which Swift can deal with:
let arr2 = (arr as Array).map { $0 as? String ?? "" }
Now arr2 is a pure Swift [String] array.

Resources