Farhad-Taran
Farhad-Taran

Reputation: 6512

Swift, can't create a dictionary to hold key values?

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>!'

Upvotes: 0

Views: 536

Answers (2)

Hendrik
Hendrik

Reputation: 940

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.

Upvotes: 1

HighFlyingFantasy
HighFlyingFantasy

Reputation: 3789

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.

Upvotes: 2

Related Questions