I change your definition of MyItem and add extension for printing.
class MyItem {
var id: Int?
var name: String?
init(id: Int?, name: String?){
self.id = id
self.name = name
}
}
extension MyItem: Printable {
var description: String {
return "\(self.id!): \(self.name!)"
}
}
And convert source string to a collection:
var source = "[{ \"id\": 1, \"name\": \"test\" },{ \"id\": 2, \"name\": \"test\" }]"
var results: [MyItem] = []
var err:NSError?
var obj:AnyObject? = NSJSONSerialization.JSONObjectWithData(source.dataUsingEncoding(NSUTF8StringEncoding)!, options:nil, error:&err)
if let items = obj as? NSArray {
for itemDict in items as [NSDictionary] {
var item: MyItem = MyItem(id: itemDict.valueForKey("id")?.integerValue, name: itemDict.objectForKey("name") as? String)
results.append(item)
}
}
println(results)
Some nil cases aren't considered. Just give you a example. You can use this popular lib: https://github.com/SwiftyJSON/SwiftyJSON and trace code in detail if interested.