将具有枚举值的Swift字典转换为NSDictionary [英] Convert Swift Dictionary With Enum Value To NSDictionary
问题描述
如果我有类型为Dictionary<String, MyEnum>
的字典,则无法弄清楚如何将其转换为NSDictionary,因此可以通过NSJSONSerialize.dataWithJSONObject
将其序列化为JSON.
If I have a dictionary with the type Dictionary<String, MyEnum>
, I cannot figure out how to convert it to an NSDictionary so I can serialiaze it to JSON via NSJSONSerialize.dataWithJSONObject
.
编译器告诉我"Dictionary<String, MyEnum> is not convertible to NSDictionary
".我是否需要使用枚举的字符串值la la创建新的字典
The compiler tells me that "Dictionary<String, MyEnum> is not convertible to NSDictionary
". Do I need to create a new dictionary with the string values of the enum a la
var newDict = Dictionary<String, String> (or <String, AnyObject>);
for (key, val) in oldDict {
newDict[key] = val;
}
还是有更好的方法?
推荐答案
NSJSONSerialize
和朋友只能处理与JSON本机数据相对应的NSObject子项的小子集(NSNumber,NSString,NSArray,NSDictionary和NSNull).类型.另外,如果键和值都为NSObject或固有地可转换为NSObject(字符串和数字类型),则只能将Dictionary转换为NSDictionary.
NSJSONSerialize
and friends can only deal with small subset of NSObject children (NSNumber, NSString, NSArray, NSDictionary, and NSNull) that correspond to the JSON native data types. In addition, a Dictionary can only be converted to an NSDictionary if both the key and value are NSObject or inherently convertible to NSObject (String and numeric types).
要序列化Dictionary,您需要将Enum转换为那些NSJSONSerialize数据类型之一,类似于您的示例:
In order to serialize your Dictionary you'll need to convert the Enum to one of those NSJSONSerialize data-types, similar to your example:
enum MyEnum : String {
case one = "one"
case two = "two"
}
let dict = ["one":MyEnum.one, "two":MyEnum.two]
var newDict = Dictionary<String, String>()
for (key, val) in dict {
newDict[key] = val.rawValue
}
let data = NSJSONSerialization.dataWithJSONObject(newDict, options: .allZeros, error: nil)
作为一种替代方法,由于这种操作相当普遍,因此您可能需要考虑将此类别添加到Dictionary中,这为它提供了一个方便的map
函数:
As an alternative, since this kind of manipulation is fairly common, you might want to consider adding this category to Dictionary, which gives it a convenient map
function:
extension Dictionary {
init(_ pairs: [Element]) {
self.init()
for (k, v) in pairs {
self[k] = v
}
}
func map<K: Hashable, V>(transform: Element -> (K, V)) -> [K: V] {
return Dictionary<K, V>(Swift.map(self, transform))
}
}
完成后,转换就很简单:
Once that's done, the conversion is simply:
let mapped = dict.map { (key, value) in (key, value.rawValue) }
这篇关于将具有枚举值的Swift字典转换为NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!