Swift 元素作为任意对象vs元素vs任意对象?
阅读苹果的代码,我看到了以下内容(谈论钥匙链服务):Swift 元素作为任意对象vs元素vs任意对象?,swift,casting,optional,keychainitemwrapper,Swift,Casting,Optional,Keychainitemwrapper,阅读苹果的代码,我看到了以下内容(谈论钥匙链服务): 任何对象的用途是什么? 我认为可以简化为 query[kSecAttrService as String] = service as AnyObject 有线索吗 以下是苹果公司样本的完整片段: private static func keychainQuery(withService service: String, account: String? = nil, accessGroup: String? = nil) -> [St
任何对象的用途是什么?
我认为可以简化为
query[kSecAttrService as String] = service as AnyObject
有线索吗
以下是苹果公司样本的完整片段:
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
}
也许这段代码是来自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
}
谁说苹果的样本必须包含完美无瑕的代码?谁说苹果的样本必须包含完美无瑕的代码?您已从
AnyObject
移动到Any
。你能告诉我为什么吗?因为在Swift 3+中,未指定的值类型是Any
,未指定的引用类型是AnyObject
。查询字典仅包含值类型。您已从AnyObject
移动到Any
。你能告诉我为什么吗?因为在Swift 3+中,未指定的值类型是Any
,未指定的引用类型是AnyObject
。查询字典仅包含值类型。