简体   繁体   English

扩展可选 <Dictionary<String, AnyObject> &gt;

[英]Extending Optional<Dictionary<String, AnyObject>>

I would like to make an extension on Optional<Dictionary<String, AnyObject>>. 我想对Optional <Dictionary <String,AnyObject >>进行扩展。 How can I write this? 我该怎么写?

I was expecting it to be something like 我原以为它会像

extension Optional where 
Wrapped : Dictionary,
Key : String,
Value : AnyObject { ... }

but it wants Dictionary to take the parameters directly, and even if this worked I expect it would complain that String was not a protocol. 但是它希望Dictionary直接采用参数,即使这样行​​之有效,我也希望它会抱怨String不是协议。 So I try 所以我尝试

extension Optional where Wrapped : Dictionary<String, AnyObject> { ... }

but here it complains that type 'Wrapped' constrained to non-protocol type 'Dictionary<String, AnyObject>' 但是在这里它抱怨type 'Wrapped' constrained to non-protocol type 'Dictionary<String, AnyObject>'

use dot syntax to access the Key and Value of Wrapped. 使用点语法访问“包装的键和值”。

extension Optional where Wrapped: DictionaryLiteralConvertible, Wrapped.Key: StringLiteralConvertible, Wrapped.Value: AnyObject {
    func doSomething() {
        print("did it")
    }
}

now you can call this: Optional(["asdf":123]).doSomething() 现在您可以称之为: Optional(["asdf":123]).doSomething()

but not this: Optional([123:123]).doSomething() 但不是这个: Optional([123:123]).doSomething()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法转换类型[[String:AnyObject] ?. Type”(也称为“可选” <Dictionary<String, AnyObject> &gt; .Type)到期望的参数类型 - Cannot convert value of type '[String : AnyObject]?.Type' (aka 'Optional<Dictionary<String, AnyObject>>.Type) to expected argument type Swift-[NSObject:AnyObject]! 不是“字典”的子类型 <String, AnyObject> - Swift - [NSObject : AnyObject]!' is not a subtype of 'Dictionary<String, AnyObject> (键:AnyObject,值:AnyObject)不能转换为&#39;Dictionary <String, AnyObject> - (key: AnyObject, value: AnyObject) is not convertible to 'Dictionary<String, AnyObject> 解包可选时,“ AnyObject”不可转换为“ String” - 'AnyObject' is not convertible to 'String' while unwrapping optional 无法到达objectForKey-[String:AnyObject]作为字典 - Can't reach objectForKey - [String : AnyObject] as dictionary Swift-使用&#39;as!时为零! 字典 <String, AnyObject> &#39; - Swift - Nil when using 'as! Dictionary<String, AnyObject>' 使用溢出的整数声明字典[String:AnyObject] - Declare dictionary [String:AnyObject] with overflowing Integers SwiftyJSON并添加到现有的[String:AnyObject]字典中 - SwiftyJSON and adding to existing [String: AnyObject] dictionary swift的最新版本:[String,String?]不能转换为字典<String, AnyObject> - Latest version of swift: [String, String?] is not convertible to Dictionary<String, AnyObject> 将[String:AnyObject]类型的字典分配给[String:String]会产生nil错误 - Assigning a dictionary of type [String:AnyObject] to [String: String] gives nil error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM