Ios 将具有枚举值的Swift字典转换为NSDictionary
如果我有一个类型为Ios 将具有枚举值的Swift字典转换为NSDictionary,ios,objective-c,json,swift,Ios,Objective C,Json,Swift,如果我有一个类型为dictionary的字典,我就不知道如何将它转换为NSDictionary,这样我就可以通过NSJSONSerialize.dataWithJSONObject将它序列化为JSON 编译器告诉我“字典不能转换为NSDictionary”。我是否需要使用enum a la的字符串值创建一个新字典 var newDict = Dictionary<String, String> (or <String, AnyObject>); for (key, val
dictionary
的字典,我就不知道如何将它转换为NSDictionary,这样我就可以通过NSJSONSerialize.dataWithJSONObject
将它序列化为JSON
编译器告诉我“字典不能转换为NSDictionary
”。我是否需要使用enum a la的字符串值创建一个新字典
var newDict = Dictionary<String, String> (or <String, AnyObject>);
for (key, val) in oldDict {
newDict[key] = val;
}
var newDict=字典(或);
用于旧字典中的(键,val){
newDict[key]=val;
}
还是有更好的方法?
NSJSONSerialize
和friends只能处理与JSON本机数据类型相对应的NSObject子对象(NSNumber、NSString、NSArray、NSDictionary和NSNull)的一小部分。此外,如果键和值都是NSObject或本质上可转换为NSObject(字符串和数字类型),则字典只能转换为NSDictionary
为了序列化字典,您需要将枚举转换为以下NSJSONSerialize数据类型之一,类似于您的示例:
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)
完成后,转换简单:
let mapped = dict.map { (key, value) in (key, value.rawValue) }
是的,我怀疑是这样的。我非常期待使用本机Swift方法来处理JSON,因为如果这确实是解决方案,那么在处理JSON繁重的代码时,我最好不要使用enum,我倾向于将NSJSONSerialization封装在依赖于JSONSerializable协议的功能中,该协议包括一个将对象转换为JSONSerializable形式的
convertToJson
对象。然后,像您在这里使用的简单枚举就可以实现该方法,如return rawValue
Ah。一般来说,这是一个很好的方法。我只是有一个例子,这是一个问题,但是,所以我可能只是摆脱了我的项目中的枚举。无论如何,我对它做的并不多,只是习惯于使用Java时代的枚举。谢谢你的指点。
let mapped = dict.map { (key, value) in (key, value.rawValue) }
public protocol EnumCollection: Hashable {
static func cases() -> AnySequence<Self>
static var allValues: [Self] { get }
}
public extension EnumCollection {
public static func cases() -> AnySequence<Self> {
return AnySequence { () -> AnyIterator<Self> in
var raw = 0
return AnyIterator {
let current: Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: self, capacity: 1) { $0.pointee } }
guard current.hashValue == raw else {
return nil
}
raw += 1
return current
}
}
}
public static var allValues: [Self] {
return Array(self.cases())
}
}
public enum ScreenName: String, EnumCollection
{
case HomeView = "Home View"
case SignUpViewController = "Domain Validate View"
var name: String {
get { return String(describing: self) }
}
var description: String {
get { return String (self.rawValue) }
}
// a dictionary mapping the raw values to the values
static var allValuesDictionary: [String : String]{
var values = [String : String]()
let mirror = Mirror(reflecting: ScreenName.allValues)
for (_, v) in mirror.children{
guard let screenName = v as? ScreenName else{continue}
values[screenName.name] = screenName.description
}
return values
}
}
<HomeView, "Home View">, <SignUpViewController, "Domain Validate View">