元素作为AnyObject vs元素vs AnyObject?

时间:2018-10-27 16:44:18

标签: swift casting optional keychainitemwrapper

阅读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
}

1 个答案:

答案 0 :(得分:2)

也许代码片段来自一些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
}