我正在尝试使用以下代码扩展Dictionary:
extension Dictionary where Key: ExpressibleByStringLiteral, Value: AnyObject {
var jsonString: String? {
if let dict = (self as AnyObject) as? Dictionary<String, AnyObject> {
do {
let data = try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions(rawValue: UInt.allZeros))
if let string = String(data: data, encoding: String.Encoding.utf8) {
return string
}
} catch {
print(error)
}
}
return nil
}
}
我在其中写类似的内容:
let x: [String: String] = ["": ""]
x.jsonString
我收到此错误:
Value of type '[String: String]' as no member 'jsonString'
我想念什么吗?
答案 0 :(得分:2)
由于String
是一个值类型,请查找它为
public struct String {
和AnyObject
仅引用类的任何实例,并且等效于Objective-C中的id
,因此x的此声明
[String: String]
不适合[String: AnyObject]
因为Any
引用了类, struct 或枚举的任何实例,因此它非常适合
答案 1 :(得分:2)
根本不需要约束字典值类型:
extension Dictionary where Key: ExpressibleByStringLiteral {
var jsonString: String? {
guard let data = try? JSONSerialization.data(withJSONObject: self)
else { return nil }
return String(data: data, encoding: .utf8)
}
}