我正在尝试创建一个字典扩展名,其中Dictionary的类型为< String,AnyObject>。
I am trying to create a dictionary extension where Dictionary is of the type <String, AnyObject>.
正在寻找许多地方,尝试不同的方法,但是他们似乎都没有工作。这是其中之一:
Was looking in many places and trying different approaches, but none of them seemed to work. This was one of them:
extension Dictionary where <String, AnyObject>{ var jsonString:String { return "" } }另一种方法因为某些原因实际上没有起作用:
extension Dictionary where Key:Hashable, Value:AnyObject { var jsonString:String { do { let stringData = try NSJSONSerialization.dataWithJSONObject(self, options: NSJSONWritingOptions.PrettyPrinted) if let string = String(data: stringData, encoding: NSUTF8StringEncoding){ return string } }catch _ { } return "" } }得到:参数类型'Dictionary'不符合预期AnyObject的类型
Got: Argument type 'Dictionary' does not conform to expected type of 'AnyObject'
推荐答案> = 3.1
从3.1起,我们可以做具体的扩展,例如:
>=3.1
From 3.1, we can do concrete extensions, ie:
extension Dictionary where Key == String {}<3.1
我们不能具体具体的具体类型,例如:
<3.1
We can not conform concrete types w/ concrete generics, ie:
extension Dictionary where Key == String然而,因为Dictionary符合序列,我们可以使用具体的泛型符合协议类型,所以我们可以这样做:
However, because Dictionary conforms to sequence and we can conform protocol types w/ concrete generics, we could do:
extension Sequence where Iterator.Element == (key: String, value: AnyObject) { func doStuff() {...否则,我们可以约束我们的密钥到一个符合以下条件的协议:
Otherwise, we can constrain our key to a protocol that string conforms to like this:
extension Dictionary where Key: StringLiteralConvertible, Value: AnyObject { var jsonString: String { return "" } }根据您更新的答案。 Json序列化需要一个对象,Swift Dictionaries是结构体。您需要转换为 NSDictionary 您必须指定 Key 以符合 NSObject 正确转换为 NSDictionary 。
As per your updated answer. Json serialization needs an object, Swift Dictionaries are structs. You need to convert to an NSDictionary You must specify Key to conform to NSObject to properly convert to an NSDictionary.
小笔记:字典已经键入约束键为 Hashable ,所以你的原始约束不会添加任何东西。
Small note: Dictionaries already type constrain Key to be Hashable, so your original constraint wasn't adding anything.
extension Dictionary where Key: NSObject, Value:AnyObject { var jsonString:String { do { let stringData = try NSJSONSerialization.dataWithJSONObject(self as NSDictionary, options: NSJSONWritingOptions.PrettyPrinted) if let string = String(data: stringData, encoding: NSUTF8StringEncoding){ return string } }catch _ { } return "" } }
请注意,字典必须符合此类型才能访问扩展名。
Note, that the dictionaries must conform to this type to access the extension.
let dict = ["k" : "v"]将成为 [String:String] ,所以你必须是明确的在声明中:
Will become type [String : String], so you must be explicit in declaring:
let dict: [NSObject : AnyObject] = ["k" : "v"]更多推荐
字典的扩展,其中< String,AnyObject>
发布评论