swiftcastingoption-typekeychainitemwrapper

element as AnyObject vs element vs AnyObject?


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
}

Solution

  • 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
    }