Swift Array addObjects to NSMutableArray - ios

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.

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") ?? ""

How to Sort using NSMutableArray?

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())

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.

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.

NSMutableArray cast to swift Array of custom type

I'd like to figure out how to specify or cast an NSMutableArray to a swift Array of a custom type. I currently have 2 files:
First file requires an NSMutableArray for its functionality (passed by reference, ability to remove particular objects with indices I don't know)
Second file uses a Swift array (better memory / throwaway array), with a custom type, which I declare using
let newArray: [CustomType]!
I need to pass the NSMutableArray in as a parameter to a function in the second file, which requires a [CustomType]. When simply calling it:
let newVC = UIViewController(array: mutableArray)
it keeps telling me 'CustomType' is not identical to 'AnyObject'. I've tried calling the function using mutableArray as [CustomType], which does not work either. How can I make the swift Array function accept my NSMutableArray?
This works for me:
var swiftArray = NSArray(array:mutableArray) as Array<CustomType>
swiftArray is then a Swift array of objects of CustomType. You can pass the array and iterate over it as you would expect.
What I needed was this:
let newVC = UIViewController(array: mutableArray as AnyObject as [CustomType])

Resources