我开始使用Swift 3开发并且我变得疯狂。以下情况:
(state) => ({
query: state.routing.locationBeforeTransitions.query.q,
results: state.userResults,
searchInFlight: state.searchInFlight
})
哪种方式是持久存储class subObject
{
var name : String
var list : [Int]
init( _name : String, _list : [Int] ){
self.name = _name
self.list = _list
}
}
class mainObject
{
var subObjectList : [subObject]
init( _list : [subObject] ){
self.subObjectList = _list
}
}
var data : [mainObject]
的最新技术。我已经尝试过var data : [mainObject]
和.plist
。
抱歉,但我的英语更糟。
答案 0 :(得分:0)
NSCoding
,因为这些类不是NSObject
的子类。
由于两个类中的所有属性都符合属性列表,因此您可以添加计算属性propertyListRepresentation
和适当的初始化程序。
类名应该以大写字母开头,以下划线开头的参数在Swift中是不寻常的。
class SubObject
{
var name : String
var list : [Int]
init(name : String, list : [Int] ){
self.name = name
self.list = list
}
init?(dictionary : [String:Any]) {
guard let name = dictionary["name"] as? String,
let list = dictionary["list"] as? [Int] else { return nil }
self.name = name
self.list = list
}
var propertyListRepresentation : [String:Any] {
return ["name" : name, "list" : list]
}
}
class MainObject
{
var subObjectList : [SubObject]
init(list : [SubObject] ){
self.subObjectList = list
}
init(propertyList : [[String:Any]] ){
self.subObjectList = propertyList.flatMap{ SubObject(dictionary: $0) }
}
var propertyListRepresentation : [[String:Any]] {
return subObjectList.map{ $0.propertyListRepresentation }
}
}
使用它:
let subs = [SubObject(name: "Foo", list: [1, 2, 3]), SubObject(name: "Bar", list: [4, 5, 6])]
let main = MainObject(list: subs)
let list = main.propertyListRepresentation
let data = try! PropertyListSerialization.data(fromPropertyList: list, format: .xml, options: 0)
print(String(data:data, encoding: .utf8)!)
let restoredList = try! PropertyListSerialization.propertyList(from: data, format: nil) as! [[String:Any]]
let restoredMain = MainObject(propertyList: restoredList)