0

I want to create a dictionary to hold these values but I get the following error

import Security
var keychainQuery: Dictionary =

            [
                kSecClass: kSecClassGenericPassword,
                kSecAttrService: service,
                kSecAttrAccount: userAccount,
                dataFromString: kSecValueData
            ]

Cannot convert the expression's type 'Dictionary' to type '@lvalue Unmanaged<AnyObject>!'
Farhad-Taran
  • 6,282
  • 15
  • 67
  • 121

2 Answers2

2

In most cases with Swift, I've found it much less painful to declare the types of the dictionary. In your case:

var keychainQuery: Dictionary<String, AnyObject> = [
    ...
]

Should work.

HighFlyingFantasy
  • 3,789
  • 2
  • 26
  • 38
  • It doesn't work since keys like kSecClass are of type Unmanaged. Even if you pass that as the Dictionaries type, it will fail since AnyObject and Unmanaged aren't hashable - they don't conform to the Hashable protocol. – Hendrik Jul 22 '14 at 12:58
1

As far as I know for now, building a Keychain query with a Swift Dictionary is not possible. Keys like kSecClass are of a non-hashable type and so can't be put in a Dictionary (that strictly needs items that share the same protocol btw.).

One of the ways I have seen to circumvent this problem is to use an NSDictionary and pass keys and values as Arrays. This code only seems to work in Xcode 6 Beta 1.

var query = NSMutableDictionary(objects: [kSecClassGenericPassword, service, account, secret], forKeys: [kSecClass, kSecAttrService, kSecAttrAccount, kSecValueData])

Another approach can be seen on this Stackoverflow answer. Based on that approach you would convert all the key and value constants to Strings using the \() syntax. The query would then look like this:

var query = ["\(kSecClass)": "\(kSecClassGenericPassword)", "\(kSecAttrService)": service, "\(kSecAttrAccount)": account, "\(kSecValueData)": secretData]

I tested this solution and got an error saying that I'm trying to add already existing keys. So this doesn't seem to work either.

Community
  • 1
  • 1
Hendrik
  • 940
  • 8
  • 14