0

Reading Apple's code I've seen the following (talking about Keychain services):

query[kSecAttrService as String] = service as AnyObject?

What's the purpose of AnyObject??

I think it could be simplified as

query[kSecAttrService as String] = service as AnyObject

Any clue?

This is the entire snippet from Apple's sample:

private static func keychainQuery(withService service: String, account: String? = nil, accessGroup: String? = nil) -> [String : AnyObject] {
    var query = [String : AnyObject]()
    query[kSecClass as String] = kSecClassGenericPassword
    query[kSecAttrService as String] = service as AnyObject?

    if let account = account {
        query[kSecAttrAccount as String] = account as AnyObject?
    }

    if let accessGroup = accessGroup {
        query[kSecAttrAccessGroup as String] = accessGroup as AnyObject?
    }

    return query
}
Lorenzo B
  • 33,216
  • 24
  • 116
  • 190

1 Answers1

2

Maybe the snippet is from some Swift 2 code, in Swift 3+ it's

private static func keychainQuery(withService service: String, account: String? = nil, accessGroup: String? = nil) -> [String : Any] {
    var query = [String : Any]()
    query[kSecClass as String] = kSecClassGenericPassword
    query[kSecAttrService as String] = service

    if let account = account {
        query[kSecAttrAccount as String] = account
    }

    if let accessGroup = accessGroup {
        query[kSecAttrAccessGroup as String] = accessGroup
    }

    return query
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • You moved from `AnyObject` to `Any`. Can you tell me why? – Lorenzo B Oct 27 '18 at 16:59
  • 1
    Because in Swift 3+ the unspecified value type is `Any` and the unspecified reference type is `AnyObject`. The query dictionary contains only value types. – vadian Oct 27 '18 at 17:01