我有以下类(在实际聊天中,类是NSManagedObject,为了清晰起见,我对其进行了简化)
import Foundation
class Chat: Hashable {
public var id: Int32?
public var token: String?
public var title: String?
var hashValue: Int {
return ObjectIdentifier(self).hashValue
}
static func ==(lhs: Chat, rhs: Chat) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
}
Set
。因此我尝试复制相同的类型)
let chat1 = Chat()
chat1.id = 1
chat1.token = "aU7nanPu"
chat1.title = "Chat Title 1"
let chat2 = Chat()
chat2.id = 2
chat2.token = "948dfjh4"
chat2.title = "Chat Title 2"
let chat3 = Chat()
chat3.id = 3
chat3.token = "1321sjadb"
chat3.title = "Chat Title 3"
var chats = Set<Chat>()
chats.insert(chat1)
chats.insert(chat2)
chats.insert(chat3)
现在,我想将数据转换为JSON,将其发送到服务器进行处理。(我将Alamofire与SwiftyJSON一起使用)因此我首先使用以下代码将其转换为Dictionary。
var resultDict = [Int:Any]()
for (index, chat) in chats.enumerated() {
var params = ["id" : chat.id!, "token": chat.token!, "title": chat.title!] as [String : Any]
resultDict[index] = params
}
这给了我以下输出
[2:[“id”:3,“token”:“1321sjadb”,“title”:“Chat title 3”],0:
“token”:“948dfjh4”,“title”:“聊天标题2”]]
let jsonData = try! JSONSerialization.data(withJSONObject: resultDict, options: .prettyPrinted)
这给了我一个错误,它说
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid (non-string) key in JSON dictionary
我的问题是,我如何转换
resultDict
PS:如果有人想玩代码,这是小提琴:
https://swift.sandbox.bluemix.net/#/repl/597833e605543472066ad11e