元素作为 AnyObject vs 元素 vs AnyObject?

element as AnyObject vs element vs AnyObject?

阅读 Apple 的代码我看到了以下内容(谈论钥匙串服务):

query[kSecAttrService as String] = service as AnyObject?

AnyObject? 的目的是什么?

我觉得可以简化为

query[kSecAttrService as String] = service as AnyObject

有线索吗?

这是 Apple 样本的完整片段:

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
}

也许该片段来自某些 Swift 2 代码,在 Swift 3+ 中是

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
}