Ambiguous use of 'mutableCopy()' Swift3 - ios

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

Related

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.

Retrieving bool array from NSUserdefaults in swift

I have defined an array like this in my iOS app
var array=[Bool]()
and assigning some bool values to this.After that I am storing this array in my user defaults in this way.
userDefaults.setObject(dm.array, forKey: "array")
Now I want to retrievw this array. So I did like this
dm.array=userDefaults.arrayForKey("array") as! Array
But here im getting an error
Down cast from '[AnyObject]?' to 'Array' only unwraps optional; did you mean to use '!'?
array = userDefaults.objectForKey("array") as? [Bool] ?? [Bool]()

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.

How can NSMutableArray add object using let in swift

I created a NSMutableArray in swift using let and
when I add addObject in the mutableArray then it will add it even though I
used the let to assign a constant. Can anyone explain how let works in swift? If it doesn't allow you to add value in later then how is the following
code working?
let arr : NSMutableArray = [1,2,3,4,5]
arr.addObject(6)
println(arr)
Classes are reference types, and NSMutableArray is a class.
Foundation's NSMutableArray is different from Swift's Array: the latter is a value type.
If you create a constant NSMutableArray:
let ns: NSMutableArray = ["a", "b"]
then this works:
ns.addObject("c")
but this doesn't:
ns = ["d", "e"] // nope!
because you can change the content of the reference but you can't change what is assigned to the constant.
On the other hand, with Swift's Array:
let sw: [String] = ["a", "b"]
the constant can't be changed because it's a value, not a reference.
sw.append("c") // nope!
Doc: Structures and Enumerations Are Value Types and Classes Are Reference Types
disclaimer: this answer only applies to NS type data structures, please see #Eric D's answer for the full picture
let when used with a class just means the variable cant be changed, eg, to another array. If you dont want the array to be editable, use a normal NSArray and not a mutable one
let arr : NSMutableArray = [1,2,3,4,5]
arr = [1,2,3,4,5] //error trying to assign to a let variable that has already been assigned
arr.addObject(6) //fine because we are not changing what is assigned to arr, but we are allowed to change the object that is assigned to arr itself
I think your understanding of what a constant variable is, is a bit too strict.

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