can not add item to NSMutableDictionary in swift iOS

Farhad-Taran picture Farhad-Taran · Jun 28, 2014 · Viewed 8k times · Source

I want to add the following items to a NSMutableDictionary but I get the following error

could not find an overload for setObject that accepts the following arguments


import Security

var returnDictionary = NSMutableDictionary()

returnDictionary.setObject(anObject: kSecClassGenericPassword, forKey: kSecClass)

when I browse to security.h file, the attributes are shown to be declared as below:

var kSecClass: Unmanaged<AnyObject>!
var kSecClassGenericPassword: Unmanaged<AnyObject>!

Answer

Yatheesha B L picture Yatheesha B L · Jun 28, 2014

The declaration of function is func setObject(anObject: AnyObject!, forKey aKey: NSCopying!)

where , anObject : A strong reference to the object is maintained by the dictionary. Raises an NSInvalidArgumentException if anObject is nil. If you need to represent a nil value in the dictionary, use NSNull.

aKey : The key for value. The key is copied (using copyWithZone:; keys must conform to the NSCopying protocol). Raises an NSInvalidArgumentException if aKey is nil. If aKey already exists in the dictionary anObject takes its place.

In your case kSecClass doesn't conforms to NSCopying protocol , therefore it is giving you Error.

Try using returnDictionary = NSMutableDictionary(objects: [kSecClassGenericPassword], forKeys: [kSecClass])

Also the below code should work Using Swift with Cocoa and Objective-C

var kSecClassSwift: NSString = kSecClass.takeRetainedValue() as NSString
returnDictionary.setObject(accessGroup, forKey: kSecClassSwift)

Due to the bug in Xcode 6 beta it is not working now , I hope in for the next release apple will fix it.